List Comprehension & Lambda Functions in Python
List comprehension took me a while to get used to, lambda functions more. Both serve to make Pythonic code simpler and easier. Knowing these functions helps to build more efficient code. Here's what I’ve learnt...
List comprehension is just a fancy way of creating a list using a loop.
ChatGPT broke it down for me to..
“Give me a list of these values, built from this sequence, following this rule.”
It’s an alternate method than to using a for loop with a set of instructions to build the new list.
The syntax for using list comprehension is:
1
2
3
4
5
6
7
8
9
10
[i for i in iterable if expression]
# OR
[
result → what you want to put in the list
for each item → loop over the data
in iterable → the data source
if condition → optional filter
]
It’s also regarded as being more efficient as there are many sets of instructions not required, like having to recursively use .append().
To show you the differences using visuals:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Without list comprehension
evens = []
for i in range(10):
if i % 2 == 0:
evens.append(i)
print(evens)
# [0, 2, 4, 6, 8]
# With list comprehension
evens = [i for i in range(10) if i % 2 == 0]
print(evens)
# [0, 2, 4, 6, 8]
By this point, I was thinking about why it’s more efficient, there are only a few lines of code taken away.
Once we’re introduced to DSA, we start to understand why even tiny differences in how code runs can greatly affect performance.
Using List Comprehension
The best you can do with list comprehension is use a lot of practice. The course contents for this one just run over different examples.
Unpacking a String Into a List
1
2
3
var_a = "Sheikh"
lst = list(var_a)
print(lst) # ["S", "h", "e", "i", "k", "h"]
Generating a List of Numbers
1
2
3
numbers = [number for number in range(10)]
print(numbers)
# [0,1,2,3,4,5,6,7,8,9]
Using The Result of a Function
1
2
3
cubes = [num ** 3 for num in range(10)]
print(cubes)
# [1, 8, 27, 64, 125, 216, 343, 512, 729]
Using If Conditions
1
2
3
even_numbers = [num for num in range(21) if num % 2 == 0]
print(even_numbers)
# [0,2,4,6,8,10, 12, 14, 16, 18, 20]
Return Tuple Values Inside a List
1
2
squares = [(i, i ** i) for i in range(10)]
# [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]
Flattening a 3 Dimensional Array
This one took me a little while to get used to. Still would say that I am working my way around it. I just need to be able to grasp the concept completely.
There are many scenarios of having to unpack a list from within a list. I would spend some time here if possible.
1
2
list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
flattened_list = [number for row in list_of_list for number in row]
I found this a little confusing at first. I used ChatGPT to help explain it to me a little better, and I wanted something a little more challenging to help get a better idea as to what is happening.
Here is what it came with:
1
2
3
4
5
6
7
8
9
[number for new_list1 in list_of_lists
for new_list2 in new_list1
for new_list3 in new_list2
for number in new_list3]
# new_list1 → first-level sublist
# new_list2 → second-level sublist
# new_list3 → third-level sublist
# number → the actual value we want to collect
💡Tip: Think of a new list being generated each time you use a
forclause. The lastfordetermines the values that appear in the flattened list, while the previous ones are just there to unpack each level of nesting.
Lambda Function
This is regarded as being an anonymous function without having to define a name for it. It is primarily used for having a function within a function.
A lambda function can take any number of arguments but can only have one expression.
Creating a Lambda Function
The syntax to creating a lambda function is calling the lambda function, listing the parameters, then defining the expression for it to use.
1
2
3
4
5
# Syntax
x = lambda parameters: expression
x = lambda param1, param2, param3: param1 * param2+ param3
print(x(arg1, arg2, arg3))
Here is a better example to see the difference in using a proper function against a lambda function.
1
2
3
4
5
6
7
8
def add_two_nums(a, b):
return a + b
print(add_two_nums(2, 3)) # 5
# Using the lambda function instead:
add_two_nums = lambda a, b: a + b
print(add_two_nums(2,3)) # 5
Using a Lambda Inside Another Function
1
2
3
4
5
def power(x):
return lambda n : x ** n
cube = power(2)(3) # Now needs two args in two brackets, function uses one, and then lambda uses one
print(cube) # 8
Summary
Hopefully, by the end of this post, you have been able to gather as much as I have about list comprehension and using the lambda function.
If I were to summarise, I would say that list comprehension is a function itself and knows how to append a result to a list. That result is the function or expression you provide it with.
It only begins to get complicated when we start trying to flatten 3d lists.
With the lambda function, it’s more about using an anonymous function to access the features of functions within a function.
These are both methods of using an existing function available within Python, but using a shorthand version of it.