List Comprehension in python allows us to build a list in a different way. Basically, it is one line for loop built inside of brackets.

See this simple example:

#normal list
l = []

for letter in 'pencil':
    l.append(letter) 
    
print(l)

#using list comprehension
l = [letter for letter in 'pencil']
print(l)

Output

['p', 'e', 'n', 'c', 'i', 'l']
['p', 'e', 'n', 'c', 'i', 'l']

You can see both produce the same output but with the list comprehension, it can be done with a single line of code.

Examples:

#Square of number in range 1 to 10
sqr = [x**2 for x in range(1,11)]
print(sqr)

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Below Example uses if statement

#even numbers from 1 to 20 using list comprehension
even = [num for num in range(1,21) if num%2 == 0]
print(even)

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Convert Celsius to Fahrenheit using list comprehension
celsius = [0,10,20.1,34.5]

fahrenheit = [((float(9)/5)*temp + 32) for temp in celsius ]

print(fahrenheit)

Output

[32.0, 50.0, 68.18, 94.1]
#nested list comprehension
lst = ['hello {}'.format(x) for x in [x for x in range(11)]]
print(lst)

Output

['hello 0', 'hello 1', 'hello 2', 'hello 3', 'hello 4', 'hello 5', 'hello 6', 'hello 7', 'hello 8', 'hello 9', 'hello 10']

Now you should feel comfortable reading and writing basic list comprehensions in Python.

Leave a Reply