As a newbie Python programmer, concepts like list comprehension may feel overwhelming in the beginning. This article is to make it easier for you to understand this very useful concept.
If you know the basics of Python, you must be familiar with lists. Python List is a collection of ordered items. List comprehension is a powerful concept in Python that provides an efficient and compact way to create lists.
Let us consider a very simple example:
Although it may look simple, what confuses most beginners is how to write them.
list_name = [<expression> for <item> in <list> if <condition>]
The <expression> can be any mathematical operation, the result of which is to be stored in the final list. In the above example, we are simply storing data i.e. storing the i-th value of the iteration, in the final list.
Similarly, if we wanted to store the square of the numbers, we can do as follows:
final_list = [i**2 for i in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Now suppose, we only want to find the square of even numbers, hence a conditional is required. We can do so by adding an if statement:
final_list = [i**2 for i in range(10) if i%2 is 0] # [0, 4, 16, 36, 64]
Let Us See More Examples