LIST COMPREHENSION IN PYTHON
In this article, we are going to be be looking into list comprehension, how to use it with some examples and some key points to note when making use of list comprehension.
List comprehension is a short and precise way of creating list based on existing list(it can also be any iterables). It combines both the for loop and creation of elements into one line and append the elements into a new list automatically which will be return as the result. Note that list comprehension always return a list as the output.
Syntax (without conditions):
[ exp for item in iterable]
With conditions:
[ exp for item in iterable if exp]
Example:
Supposed we were asked to write a code that returns a list containing the square of the first 10 integers. Using list comprehension
squares = [ x**2 for x in range (10)]
Explanation
1) To create a list comprehension, we start with the name of the new list we are creating. In this case, the name of the new list is squares
2) open a set of brackets and define the expression for the elements you want to store in the new list. In the example above, the expression is x**2
3) Then write a for loop to generate number you want to feed into the expression. In this case we have for x in range(10) . Note: the for loop will not end with a semi-colon(:)
List comprehension vs python for loop
Example
write a code to separate letter from string
using python for loop
letters = []
for i in "human":
letters.append(i)
print(letters)
Output
['h', 'u', 'm', 'a', 'n']
Using list comprehension
letters = [i for i in "human"]
List comprehension with if statement
Example
Write a code to output the first 5 even number
Using python for loop
even = []
for i in range(1,11):
if i%2==0:
even.append(i)
print(even)
Output
[2,4,6,8,10]
Using list comprehension
even = [i for i in range(1,11) if i%2==0]
List comprehension with nested for loop
Example
even = [2,4,6,8]
odd = [1,3,5,7]
even_odd = [(x,y) for x in even for y in odd]
print(even_odd)
Output
[(2, 1), (2, 3), (2, 5), (2, 7), (4, 1), (4, 3), (4, 5), (4, 7), (6, 1), (6, 3), (6, 5), (6, 7), (8, 1), (8, 3), (8, 5), (8, 7)]
List comprehension with if and else statement
Example
even_odd = ["even" if i%2 == 0 else "odd" for i in range(50)]
print(even_odd)
Output
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
NOTE
I) Avoid writing very long list comprehensions in one line ii) Every list comprehension can be rewritten in for loop, but it is not true for the other way round