Python List Comprehensions

List comprehensions represent creation of new lists from an iterable object (like a list, set, tuple, dictionary or range) that satisfy a given condition. List comprehensions contain very compact code usually a single statement that performs the task.


We want to create a list with squares of integers from 1 to 10. We can write code as:



The previous code can be rewritten in a compact way as:


squares = [x**2 for x in range(1, 11)]


print(squares)


Suppose, we want to get squares of integers from 1 to 10 and take only the even numbers from the result, we can write a list comprehension as:


even_squares = [x**2 for x in range(1, 11) if x% 2==0]


Let's take a list 'words' that contains a group of words or strings as:


words = ['Apple', 'Grapes', 'Banana', 'Orange']


We want to retrieve only the first letter of each word from the above list and store those first letters into another list 'lst'. We can write code as:

lst = []
for w in words:
lst.append(w[0])

Now, lst contains the following letters: ['A', 'G', 'B', 'O']
This task can be achieved through list comprehension as:


lst = [w[0] for w in words]