
List comprehension is very useful while working with lists. Using list comprehension, we can replace code for loops with a single expression.
Below is the syntax for list comprehension.
[<expression> for <element> in <list> if <condition>]
Example 1: Let’s look at an example by comparing how code looks like without and with a list comprehension.
Without List Comprehension
mylist = [1, 2, 3, 4, 5]
# Adding 10 to each number in mylist
for i in range(len(mylist)):
mylist[i] = mylist[i] + 10
print(mylist)
Output : [11, 12, 13, 14, 15]
With List Comprehension
mylist = [1, 2, 3, 4, 5]
# Adding 10 to each number in mylist
print([x+10 for x in mylist])
Output: [11, 12, 13, 14, 15]
In the above example, the output is the same for without using and with using list comprehension. The use of list comprehension requires lesser code.
Let’s look at the list comprehension code in detail.
[x+10 for x in mylist]
x+10 -> An output variable or expression
for
x -> Variable referencing an input sequence or list
in
mylist -> An input sequence
Example 2: Let’s look at an example with if condition. This will add only those items to the list that meet the condition.
[i for i in range(10) if i % 2 == 0]
Output : [0, 2, 4, 6, 8]
Example 3: Nested Conditions - With a Python list comprehension, you can add more than one condition.
[i for i in range(10) if i % 2 == 0 if i % 3 == 0]
Output :[0, 6]
Example 4: Using if else in List comprehension -
Syntax for this little is different from what’s mentioned above.
[f(x) if condition else g(x) for x in sequence]
Let’s looks at an example — For numbers greater than or equal 45 add 1.
For numbers below 45 add 5.
mylist = [21, 11, 49, 52, 98, 69, 43, 44, 1]
print( [x+1 if x >= 45 else x+5 for x in mylist])
Output :[26, 16, 50, 53, 99, 70, 48, 49, 6]
Example 5: Nested List comprehension
We want to convert all elements in below nested list to float.
l = [[‘40’, ‘20’, ‘10’, ‘30’], [‘20’, ‘20’, ‘20’, ‘20’, ‘20’]]
print ([[float(y) for y in x] for x in l])
Output : [[40.0, 20.0, 10.0, 30.0], [20.0, 20.0, 20.0, 20.0, 20.0]]