Python List Comprehension: Know its Syntax and Conditionals
Do you feel overwhelmed by the lengthy codes needed to manipulate lists in Python? Are you wishing for a more efficient and concise method of creating new iterables based on existing ones? Python List comprehension helps you do this. This powerful technique allows developers to generate new lists by using expressions and functions, without sacrificing speed or efficiency. But that’s not all!
In this blog, we will dive into understanding list comprehension syntax, compare it against traditional ‘for loops’, learn about lambda functions, and more.
What is List Comprehension in Python?
Python list comprehension is a powerful technique that allows developers to create new lists by applying expressions and functions to elements in an existing iterable. It provides an efficient way of creating complex list structures with minimal code, which makes it faster than using methods like ‘for loops’ or ‘map()’.
In list comprehension, you can use if conditions along with the looping expression to filter out particular items from the result generated after evaluating each element in any given sequence. This method of quickly producing complex lists through minimal code makes it significantly faster than processing a list via traditional means, like using a “for” loop.
Also Read: Difference Between List and Tuple in Python
List Comprehension Syntax
[expression for element in iterable if condition]
List comprehension is a type of programming syntax used to construct new lists from existing ones. It consists of an expression, one or multiple “for” loops, and an optional conditional statement. The result generated from the first expression will be stored in a list that can be accessed by including it within square brackets []. A for loop iterates over all values contained inside array-like objects such as tuples, lists, etc., optionally with conditions specified at each step to filter out specific items.
Creating a List of Even Numbers Without Using List Comprehension
For instance, to create a list of even numbers from 0 to 20, we can use the following code:
even_numbers = []
for num in range(21):
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers)
This will generate an output that displays all of the even numbers from 0 to 20.
Creating a List of Even Numbers Using List Comprehension
By using list comprehension, we can achieve the same result as a ‘for loop’ in fewer lines of code. For example,
even_numbers = [x for x in range(21) if x%2 == 0]
print(even_numbers)
This will generate an output that displays all of the even numbers from 0 to 20.
[0, 2, 4, 6, 8 10 12 14 16 18 20].
In the above example, [x for x in range(21) if x%2 == 0] uses list comprehension to create a new list. The code iterates through each value of ‘x’ within the given range and tests it against the remainder (modulo) operation %2. If this evaluates as True, which means that there is no reminder left from dividing by 2, then the expression before for loop (in this case just ‘X’ itself) will be stored in a newly created list. This process continues until all applicable values have been evaluated and added to the final result set.
To learn more about list comprehension, you can opt for this detailed Python course.
‘For’ Loop vs List Comprehension Python
If you want to separate the letters of a word, like “School”, you can use a ‘for’ loop. Here is an illustration that you could use:
Example: Using ‘for’ Loop
characters = []
for letter in 'school':
characters.append(letter)
print(characters)
This should give the output:
['s', 'c', 'h', 'o', 'o', 'l']
However, with list comprehension in Python, we could use a simpler code line to achieve the same result.
Example: Using List Comprehension
characters = [ letter for letter in ‘school’]
print(characters)
This should give the output:
['s', 'c', 'h', 'o', 'o', 'l']
Conditionals in List Comprehension
List comprehensions can be used with conditionals to generate modified lists from existing iterables, such as tuples. An example of this is creating a list that utilizes mathematical operators, integers, and the range() built-in function.
Given below are some conditions that we will consider here.
Using ‘if’ with List Comprehension
To use the ‘if’ statement, we will run:
even_numbers = [num for num in range(30) if num % 3 == 0]
print(even_numbers)
Output:
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
The items in the ‘even_numbers’ list will be taken from 0-27 with only those divisible by 3 being included.
‘Nested IF’ with List Comprehension
divisible_list = [num for num in range(150) if num % 3 == 0 if num % 10 == 0]
print(divisible_list)
Output:
[0, 30, 60, 90, 120]
This code will generate a list called ‘divisible_list’. This newly created list contains all numbers ranging from 0 to 149 that are both evenly divisible by 3 and 10.
‘if/else’ With List Comprehension
result = ["Yes" if num % 3 == 0 else "No" for num in range(15)]
print(result)
Output:
['Yes', 'No', 'No', 'Yes', 'No', 'No', 'Yes', 'No', 'No', 'Yes', 'No', 'No', 'Yes', 'No', 'No']
This program creates a list that contains “Yes” for any number between 0 and 14 (inclusive) if it is divisible by 3, or a “No” if not. The output, either ‘Yes’ or ‘No’ will be printed depending on whether each number from 0 to 14 is exactly divisible by three.
How to Use Nested Loops in Python List Comprehension
Now let’s see how to use regular ‘for loops’ to calculate the transpose of a matrix that needs nested iterations. We will also know how to do the same using list comprehension in Python.
Example: Matrix Transpose Using Nested Loops
result = []
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(grid[0])):
transposed_row = []
for row in grid:
transposed_row.append(row[i])
result.append(transposed_row)
print(result)
Output:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
In this example, the code will take a 3×3 grid stored in the variable ‘grid’ and transpose it by swapping its rows and columns. The result of the transposition is then assigned to another variable called ‘result’. Finally, it prints out what was created, the newly-transposed version of the original grid.
Example: Matrix Transpose Using List Comprehension
data = [[10, 20], [30, 40], [50, 60], [70, 80]]
transposed = [[row[i] for row in data] for i in range(2)]
print(transposed)
Output:
[[10, 30, 50, 70], [20, 40, 60, 80]]
The given code takes the 4×2 matrix represented by the variable data, and transposes it (swapping its rows and columns) to create a new 2×4 matrix stored in the variable ‘transposed’. It then prints out this newly created transposed matrix.
Lambda Functions and List Comprehensions
List comprehensions in Python create and modify lists quickly. They are easy to read, write, and understand, making them more user-friendly.
However, when large amounts of data need processing, lambda functions can help give your code an extra boost. They provide the same capabilities as list comprehension with fewer lines, so you get powerful solutions without taking up too much space.
Also Read: Lambda Function In Python
Example: Using Lambda Functions Inside List
letters = list(map(lambda x: x, 'school'))
print(letters)
This should give the output:
['s', 'c', 'h', 'o', 'o', 'l']
Conclusion
Python list comprehension is a powerful tool that helps developers write lists with fewer lines of code. By utilizing expressions, functions, and logical statements, list comprehension can modify existing lists or create new ones quickly and efficiently. Compared to ‘for loops’, it provides enhanced performance and ease of reading.