Advanced Coding Logic and Mental Frameworks
Advanced Python Techniques
Writing More Pythonic Code
Once you have the basics of Python down, you can start exploring more elegant ways to write your code. Python offers several powerful features that let you express complex operations concisely. These aren't just shortcuts; they often lead to code that is easier to read and more efficient. Let's dive into a few of these advanced techniques.
List Comprehensions
List comprehensions are a concise way to create lists. They provide a shorter syntax for creating a new list based on the values of an existing list. Imagine you have a list of numbers and you want to create a new list containing the square of each number. Traditionally, you might use a for loop.
squares = []
numbers = [1, 2, 3, 4, 5]
for number in numbers:
squares.append(number ** 2)
print(squares)
# Output: [1, 4, 9, 16, 25]
This works perfectly well, but a list comprehension achieves the same result in a single, more readable line.
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
# Output: [1, 4, 9, 16, 25]
The basic syntax is
[expression for item in iterable]. You can read it like a sentence: "Create a new list with the result of this expression for each item in this iterable."
You can also add a condition to filter the items from the original list. Let's say we only want the squares of the even numbers.
numbers = [1, 2, 3, 4, 5]
even_squares = [number ** 2 for number in numbers if number % 2 == 0]
print(even_squares)
# Output: [4, 16]
The syntax simply extends to [expression for item in iterable if condition]. This pattern is incredibly useful and is considered very "Pythonic"—a term used to describe code that's written in a clear, concise, and idiomatic way.
Anonymous Functions
Sometimes you need a simple function for a short task, and defining a full function with def feels like overkill. This is where lambda functions come in. A lambda function is a small, anonymous function defined with the lambda keyword.
A lambda function can take any number of arguments, but can only have one expression. The expression is evaluated and returned.
# A regular function
def add(x, y):
return x + y
# The lambda equivalent
add_lambda = lambda x, y: x + y
print(add(5, 3)) # Output: 8
print(add_lambda(5, 3)) # Output: 8
While you can assign them to a variable as shown above, their main power is in being used as throwaway functions, particularly as arguments to higher-order functions—functions that take other functions as arguments. Let's see this in action.
Map, Filter, and Reduce
These three functions are cornerstones of a programming style called functional programming. They allow you to process iterables like lists without writing explicit loops.
map
verb
The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.
Let's say we have a list of numbers as strings and we want to convert them to integers. We can map the built-in int() function over the list.
str_numbers = ['1', '2', '3', '4']
int_numbers = list(map(int, str_numbers))
print(int_numbers)
# Output: [1, 2, 3, 4]
Now, let's use map with a lambda to double every number in a list.
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
# Output: [2, 4, 6, 8]
Next is filter(). As its name suggests, it filters an iterable, returning only the items for which a function returns True.
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
# Output: [2, 4, 6]
Finally, there's reduce(). This function is a bit different. It applies a function of two arguments cumulatively to the items of a sequence, so as to reduce the sequence to a single value. To use it, you need to import it from the functools module.
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
# Output: 24
Here's how reduce works in that example: it takes the first two items (1 and 2), multiplies them to get 2. Then it takes that result (2) and the next item (3) and multiplies them to get 6. Finally, it takes that result (6) and the last item (4) and multiplies them to get the final result, 24.
Use
mapto transform every element,filterto select a subset of elements, andreduceto combine all elements into one.
Ready to test your knowledge?
What is the output of the following Python code?
numbers = [1, 2, 3, 4, 5]
[x*x for x in numbers if x % 2 == 0]
Which of the following statements about lambda functions in Python is true?
Mastering these techniques will make your Python code more concise, readable, and efficient.