A new list can be created using the values of an existing list using Python list comprehension, which offers a significantly simpler syntax.
The new list is created from an initial list. The new list is created based on the expression and condition of the list's comprehension. Python list comprehension is housed in a square bracket. The square brackets contain an expression, one or more for loops, and an optional one or more if conditions.
A for loop can be used to create a new list. The question is why use list comprehension instead of a for loop?
Advantage of python list comprehension.
- Python list comprehension requires fewer lines of code.
- List comprehension is considerably faster than processing a list using the for loop.
- It makes iteration easier.
Python list comprehension syntax.
[expression for element in iterable if condition]
Let's create odd numbers from a list of numbers using for loop and list comprehension.
new_list = []
for i in range(11):
if i%2 != 0:
new_list.append(i)
print(new_list)
Output: [1, 3, 5, 7, 9]
Let's do the same thing using list comprehension.
new_list = [x for x in range(11) if x%2 != 0]
print(new_list)
Output: [1, 3, 5, 7, 9]
The same list of odd numbers was printed with fewer lines of code using list comprehension. The expression in the list comprehension is x, the for loop is for x in range(11)
and the optional conditional statement is if x%2 != 0
. All this was wrapped in a square bracket.
Nested List Comprehension
The for loops or the if conditional statement in the python list comprehension can be nested.
#Nested for loop list comprehension
numbers = [(x, y) for x in range(1, 3) for y in range(4, 7)]
print(numbers)
Output: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6)]
#Nested if conditional list comprehension
numbers = [x for x in range(50) if x%2==0 if x%5==0]
print(numbers)
Output: [0, 10, 20, 30, 40]