Scenario 1: Let's say you have been given a list of numbers and you need to double each element in the list and store it in a new list. How would you do it?
list_numbers = [1,2,3,4]
list_double=[ ]
for element in list_numbers:
list_double.append(2*element)
print(list_double)
---> [2, 4, 6, 8]
Is there a better way of writing this? In a more Pythonic way? Enter List Comprehension!!
list_double_with_comprehension = [2*element for element in list_numbers]
print(list_double_with_comprehension)
---> [2, 4, 6, 8]
Using List comprehension, a 3-line code gets converted to a 1-line code. In general, the format for a list comprehension requires at-least 2 pieces of information.
- The expression which needs to be computed
- Iterating through the iterable
When we created list_double_with_comprehension, (2*element) is the expression which is computed and "for element in list_numbers" is the way we iterate through the original list called "list_numbers".
Scenario 2: Let's assume we have been given a list of numbers and we want to create a new list which contains only even numbers. First, let's create a list of numbers
list_nos = [1,2,5,8,9,11,12,14,18,21]
Now let's create an empty list called list_even_nos. This is how we would usually write code
list_even_nos=[ ]
for element in list_nos:
if element%2==0:
list_even_nos.append(element)
print(list_even_nos)
--> [2, 8, 12, 14, 18]
A list comprehension way of writing would be as shown below
list_even_nos_comprehension = [element for element in list_nos if element%2==0]
print(list_even_nos_comprehension)
---> [2, 8, 12, 14, 18]
We mentioned above that we need at-least 2 pieces of information to write a list comprehension. Technically, there is a 3rd piece of information required if we are trying to check for a condition. In this case, we want to check if any element in the list_nos is even. Hence,we use if element%2==0. To reiterate, the format for a list comprehension requires at-least 2 pieces of information with the 3rd piece being optional.
- The expression which needs to be computed
- Iterating through the iterable
- Condition to be checked (If required)
This covers broadly the ideas around list comprehension. More on this topic in the next post
Comments
Post a Comment