In this tutorial, we will learn about using list comprehension technique to simplify iterating a list.
List Comprehension in Mathematics:
Basically comprehension means that covering all the or a large portion of something.
If you like mathematics, lets compare Python List Comprehension with Sets in Mathematics.
For example, we can denote a set in short form.
If there is a set of more than 100 numbers, we cannot write it by hand.
However we can mention the pattern and tell the start and stopping point as shown below.
Lets say, a Set of Real Numbers from R
In the same way, we can mention a list in short form.
List Comprehension In Python:
Including the formation, we can also implement some expression in each item and create a new list from an existing list.
Syntax:
list_variable = [expression for item in iterable]
Example: [ s.lower() for word in wordList for s in word ]
When working with data, we may want to do operations in list like iterate through all the values and apply an operation.
We can do this in many ways like lambda, map, filter.
However we can do this using list comprehension.
If we need to iterate through a multi dimensional array or list, we can use list comprehension easily than using other anonymous functions.
List comprehension is compact and faster than normal functions and loops for creating list.
Long list comprehensions can be avoided to make the code user-friendly.
Example:
Lets say, we have a list of veggies and we need to convert each item as title.
Here is an example with for loop:
veggies = ['cabbage', 'carrot', 'beans', 'broccoli', 'tomato', 'potato']
new_veggies = []
for item in veggies:
new_veggies.append(item.title())
new_veggies
['Cabbage', 'Carrot', 'Beans', 'Broccoli', 'Tomato', 'Potato']
Here is how we can short this using List Comprehension:
veggies = ['cabbage', 'carrot', 'beans', 'broccoli', 'tomato', 'potato']
new_veggies = [item.title() for item in veggies]
new_veggies
['Cabbage', 'Carrot', 'Beans', 'Broccoli', 'Tomato', 'Potato']
Nested Loops in List Comprehension:
When used with for loop:
sentlist = ['Die with memories, not dreams','Aspire to inspire before we expire',
'There is no free lunch','Reality is wrong, dreams are for real']
words = []
for sentence in sentlist:
for word in sentence.split():
words.append(word)
print(words)
['Die', 'with', 'memories,', 'not', 'dreams', 'Aspire', 'to', 'inspire', 'before', 'we', 'expire', 'There', 'is', 'no', 'free', 'lunch', 'Reality', 'is', 'wrong,', 'dreams', 'are', 'for', 'real']
Using Comprehension:
sentlist = ['Die with memories, not dreams','Aspire to inspire before we expire',
'There is no free lunch','Reality is wrong, dreams are for real']
words = [ word for sentence in sentlist for word in sentence.split() ]
print(words)
['Die', 'with', 'memories,', 'not', 'dreams', 'Aspire', 'to', 'inspire', 'before', 'we', 'expire', 'There', 'is', 'no', 'free', 'lunch', 'Reality', 'is', 'wrong,', 'dreams', 'are', 'for', 'real']
Conditional Statements in List Comprehension:
The order of “If” and “for” statement is important when used together.
IF Only Conditional Statement:
#Print even numbers from a list
number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
#There can be more than one conditions
num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list)
num_list = [y for y in range(100) if y % 2 == 0 and y % 5 == 0]
print(num_list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90] [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
IF-Else Conditional Statement:
When the conditional IF statement contains else part, then it should be used before the for statement.
number_list = [ 'Even' if x%2 == 0 else 'Odd' for x in range(20)]
print(number_list)
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']