Python is a great language to learn for its ease of use and its powerful application in big data. When first learning python, there are 4 powerful concepts that can be hard to understand depending on your prior programming experience. Today, we explain these concepts in detail to help you write cleaner code.
1. A function is a pointer to a block of code
In python, a function is simply a pointer to a piece of code. Therefore, a function can call other functions, be a parameter, and can be assigned to a variable. While this may be hard to grasp at first, it is critical to understand especially when having to work on large codebases that have been worked on by multiple developers. Understanding how python handles each line of code, will enable you to easily read and dissect code.
2. Lambda function are functions created on the fly
lambda parameters: expression
Lambdas are a great way to create small anonymous functions that are needed only where they are located. Lambda are mainly used as an argument of other functions or along with built-in functions like filter.
3. List comprehension and generator
results = []
for name in directory:
results.append(name.upper())
# Above for loop written as list comprehension
results = [ name.upper() for name in directory ]
Other than a slight difference in syntax, the main difference between generators and comprehensions is that generators return a pointer to the values of the list instead of the list itself. Conserving the amount of memory used. In the example below, the syntactical difference between comprehensions and generators can be seen. List comprehension uses square brackets, whereas generators use parenthesis. By adding a print statement after your list comprehension and generator, it will be easier to see what the output is for each.
results = (name.upper() for name in directory)
4. Dictionaries can replace complicated elseif logic
test_input = '1'
# Traditional elif statement
if test_input == '1':
print('one')
elif test_input == '2':
print('two')
# Elif statement converted into dictionary
case_dict = {
'1': 'one',
'2': 'two'
}
test_output = case_dict[test_input]
print(test_output)
Have questions? Contact us today, we would love to hear from you.