|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: List Comprehension & Lambda Functions in Python |
| 4 | +description: >- |
| 5 | + 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... |
| 6 | +author: Sheikh Hussain |
| 7 | +date: 2025-12-30 17:00:00 +0000 |
| 8 | +categories: [Python, Courses] |
| 9 | +tags: [python, programming, course, 30days, day13] |
| 10 | +pin: false |
| 11 | +math: false |
| 12 | +mermaid: false |
| 13 | +render_with_liquid: false |
| 14 | +media_subpath: /assets/img/posts/ |
| 15 | +--- |
| 16 | + |
| 17 | +List comprehension is just a fancy way of creating a list using a loop. |
| 18 | + |
| 19 | +ChatGPT broke it down for me to.. |
| 20 | + |
| 21 | +> _“Give me a list of these values, built from this sequence, following this rule.”_ |
| 22 | +
|
| 23 | +It's an alternate method than to using a **for loop** with a set of instructions to build the new list. |
| 24 | + |
| 25 | +The syntax for using list comprehension is: |
| 26 | + |
| 27 | +```python |
| 28 | +[i for i in iterable if expression] |
| 29 | + |
| 30 | +# OR |
| 31 | + |
| 32 | +[ |
| 33 | + result → what you want to put in the list |
| 34 | + for each item → loop over the data |
| 35 | + in iterable → the data source |
| 36 | + if condition → optional filter |
| 37 | +] |
| 38 | +``` |
| 39 | + |
| 40 | +It's also regarded as being more efficient as there are many sets of instructions not required, like having to recursively use `.append()`. |
| 41 | + |
| 42 | +To show you the differences using visuals: |
| 43 | + |
| 44 | +```python |
| 45 | +# Without list comprehension |
| 46 | +evens = [] |
| 47 | + |
| 48 | +for i in range(10): |
| 49 | + if i % 2 == 0: |
| 50 | + evens.append(i) |
| 51 | + |
| 52 | +print(evens) |
| 53 | +# [0, 2, 4, 6, 8] |
| 54 | + |
| 55 | +# With list comprehension |
| 56 | +evens = [i for i in range(10) if i % 2 == 0] |
| 57 | + |
| 58 | +print(evens) |
| 59 | +# [0, 2, 4, 6, 8] |
| 60 | +``` |
| 61 | + |
| 62 | +By this point, I was thinking about why it's more efficient, there are only a few lines of code taken away. |
| 63 | + |
| 64 | +Once we’re introduced to <abbr title="Data Structures and Algorithms">DSA</abbr>, we start to understand why even tiny differences in how code runs can greatly affect performance. |
| 65 | + |
| 66 | +--- |
| 67 | + |
| 68 | +## Using List Comprehension |
| 69 | + |
| 70 | +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. |
| 71 | + |
| 72 | +### Unpacking a String Into a List |
| 73 | + |
| 74 | +```python |
| 75 | +var_a = "Sheikh" |
| 76 | +lst = list(var_a) |
| 77 | +print(lst) # ["S", "h", "e", "i", "k", "h"] |
| 78 | +``` |
| 79 | + |
| 80 | +### Generating a List of Numbers |
| 81 | + |
| 82 | +```python |
| 83 | +numbers = [number for number in range(10)] |
| 84 | +print(numbers) |
| 85 | +# [0,1,2,3,4,5,6,7,8,9] |
| 86 | +``` |
| 87 | + |
| 88 | +### Using The Result of a Function |
| 89 | + |
| 90 | +```python |
| 91 | +cubes = [num ** 3 for num in range(10)] |
| 92 | +print(cubes) |
| 93 | +# [1, 8, 27, 64, 125, 216, 343, 512, 729] |
| 94 | +``` |
| 95 | + |
| 96 | +### Using If Conditions |
| 97 | + |
| 98 | +```python |
| 99 | +even_numbers = [num for num in range(21) if num % 2 == 0] |
| 100 | +print(even_numbers) |
| 101 | +# [0,2,4,6,8,10, 12, 14, 16, 18, 20] |
| 102 | +``` |
| 103 | + |
| 104 | +### Return Tuple Values Inside a List |
| 105 | + |
| 106 | +```python |
| 107 | +squares = [(i, i ** i) for i in range(10)] |
| 108 | +# [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)] |
| 109 | +``` |
| 110 | + |
| 111 | +### Flattening a 3 Dimensional Array |
| 112 | + |
| 113 | +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. |
| 114 | + |
| 115 | +There are many scenarios of having to unpack a list from within a list. I would spend some time here if possible. |
| 116 | + |
| 117 | +```python |
| 118 | +list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] |
| 119 | +flattened_list = [number for row in list_of_list for number in row] |
| 120 | +``` |
| 121 | + |
| 122 | +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. |
| 123 | + |
| 124 | +Here is what it came with: |
| 125 | + |
| 126 | +```python |
| 127 | +[number for new_list1 in list_of_lists |
| 128 | + for new_list2 in new_list1 |
| 129 | + for new_list3 in new_list2 |
| 130 | + for number in new_list3] |
| 131 | + |
| 132 | +# new_list1 → first-level sublist |
| 133 | +# new_list2 → second-level sublist |
| 134 | +# new_list3 → third-level sublist |
| 135 | +# number → the actual value we want to collect |
| 136 | +``` |
| 137 | + |
| 138 | +<!--prettier-ignore--> |
| 139 | +> 💡**Tip**: Think of a new list being generated each time you use a `for` clause. The last `for` determines the values that appear in the flattened list, while the previous ones are just there to unpack each level of nesting. |
| 140 | +{: .prompt-tip} |
| 141 | + |
| 142 | +## Lambda Function |
| 143 | + |
| 144 | +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. |
| 145 | + |
| 146 | +A lambda function can take any number of arguments but can only have one expression. |
| 147 | + |
| 148 | +### Creating a Lambda Function |
| 149 | + |
| 150 | +The syntax to creating a lambda function is calling the lambda function, listing the parameters, then defining the expression for it to use. |
| 151 | + |
| 152 | +```python |
| 153 | +# Syntax |
| 154 | +x = lambda parameters: expression |
| 155 | +x = lambda param1, param2, param3: param1 * param2+ param3 |
| 156 | + |
| 157 | +print(x(arg1, arg2, arg3)) |
| 158 | +``` |
| 159 | + |
| 160 | +Here is a better example to see the difference in using a proper function against a lambda function. |
| 161 | + |
| 162 | +```python |
| 163 | +def add_two_nums(a, b): |
| 164 | + return a + b |
| 165 | +print(add_two_nums(2, 3)) # 5 |
| 166 | + |
| 167 | +# Using the lambda function instead: |
| 168 | + |
| 169 | +add_two_nums = lambda a, b: a + b |
| 170 | +print(add_two_nums(2,3)) # 5 |
| 171 | +``` |
| 172 | + |
| 173 | +### Using a Lambda Inside Another Function |
| 174 | + |
| 175 | +```python |
| 176 | +def power(x): |
| 177 | + return lambda n : x ** n |
| 178 | + |
| 179 | +cube = power(2)(3) # Now needs two args in two brackets, function uses one, and then lambda uses one |
| 180 | +print(cube) # 8 |
| 181 | +``` |
| 182 | + |
| 183 | +## Summary |
| 184 | + |
| 185 | +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. |
| 186 | + |
| 187 | +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. |
| 188 | + |
| 189 | +It only begins to get complicated when we start trying to flatten 3d lists. |
| 190 | + |
| 191 | +With the lambda function, it's more about using an anonymous function to access the features of functions within a function. |
| 192 | + |
| 193 | +These are both methods of using an existing function available within Python, but using a shorthand version of it. |
0 commit comments