List Comprehension in Python3
List
A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the same datatype. Therefore, a list that contains the same datatype variables is called homogenous lists, and those with different variable datatype are called heterogeneous lists.
Characteristics of a list
- Ordered: List stores all the elements in order.
- Mutable: List can be changed, i.e., elements can be added or deleted.
- Allows Duplicate: List allows using the duplicated item.
- Allows None: List allows having ‘None’ as an element.
Example
#creating a new empty list
colors = []
#adding elements at the initialization
colors = [ ‘White’, ‘Black’, ‘Red’, ‘Green’, ‘Blue’]
In the above code, we created a new list. A list can be initialized using [], and elements may be added later. We can also add all elements at the initialization as shown in the code.
#checking type
print(type(colors))
Output:
<class ‘list’>
#printing all elements of the list
for items in colors:
print(item, end= ‘ ’)
Output:
White Black Red Green Blue
What is List Comprehension in Python?
List comprehension is a technique that allows one to use/create a list in a single line of code.
Why do we use list comprehension?
Let’s consider a list of colors i.e.
colors = [ ‘White’, ‘Black’, ‘Red’, ‘Green’, ‘Blue’].
We want to create a new list of all the colors with ‘e’ in their name.
Let’s try to do it without using list comprehension.
Code:
colors = [‘White’, ‘Black’, ‘Red’, ‘Green’, ‘Blue’]
#creating a new empty list
#it will store the elements
newlist = []
for item in colors:
if “e” in item: #checking colors with ‘e’ in their name
newlist.append(item)
print(newlist)
Output:
[‘White’, ‘Red’, ‘Green’, ‘Blue’]
Explanation:
- We created a new list, being used further in the code to hold the values.
- Using for loop to iterate over all the elements of the main list, i.e., colors.
- Using if-else condition to evaluate whether the item consists of ‘e’ in them.
- Appending the values to the new list.
- Finally, printing the new list to check if the code worked properly.
Using list comprehension, we can do it in fewer lines of code. We will create the new list in one line of code.
Code:
colors = [‘White’, ‘Black’, ‘Red’, ‘Green’, ‘Blue’]
#Using line comprehension
newlist = [x for x in colors if "e" in x]
print(newlist)
Output:
[‘White’, ‘Red’, ‘Green’, ‘Blue’]
Explanation:
- The same list of colors is used.
- The ‘newlist’ is declared and initiated in the same line.
- x for x in colors if "e" in x can be divided in three parts, outcome-loop-condition.
- First, a loop is initiated for all items in color, i.e., for x in colors.
- Secondly, an if-else statement checks for the condition to be true, i.e., if "e" in x.
- Finally, the outcome of the statement ‘x’ is yielded as output.
- Since the outcome is directly appended to the list, a new list is created with just a single line of code.
Now, we can clearly define the concept of line comprehension on our own.
Syntax of line comprehension
newlist = [expression for item in iterable if condition == True]
An expression denotes the outcome that will be stored in the newlist. It may also hold a simple code to change the outcome that comes out of for loop.
The iterable part takes in an iterable object as input. It may be a list, tuple, set, etc.
The condition part always looks for the items that yield True.
Let’s take another example to better understand the concept:
Code:
#creating a list
in = [‘J’, ‘A’, ‘V’, ‘A’, ‘T’, ‘P’, ‘O’, ‘I’, ‘N’, ‘T’]
#using line comprehension to get all letter that are not ‘A’
out = [ letter for letter in nm if letter!= ‘A’]
#printing the new list ‘out’
print(“out”)
Output:
[‘J’, ‘V’, ‘T’, ‘P’, ‘O’, ‘I’, ‘N’, ‘T’]
Explanation:
Firstly, an iterable (list in this case) 'in' is fed to for loop. Then, the condition checks for the letters that are not 'A'. Finally, all the letters except 'A' come out as output. The new list stores the entire outcome. The print statement prints the new list.
We can also use range() function as iterable during line comprehension
#using range() in list comprehension
num = [x for x in range(10) if x < 5]
#printing the new list ‘num’
print(“num”)
Output:
[‘1’, ‘2’, ‘3’, ‘4’]
Explanation:
As we know, there are three things in a line comprehension, expression, iteration, and condition.
In this example, the range(10) is iterable. The condition 'x<5' checks for 'True' as an outcome. As soon as x becomes equal to 5, the condition starts yielding 'False'. The outcome is then stored as elements inside the list.
The expression part of the list comprehension can be used to manipulate the final output to the list.
#using range() in list comprehension
num = [x+1 for x in range(10) if x < 5]
#printing the new list ‘num’
print(“num”)
Output:
[‘2’, ‘3’, ‘4’, ‘5’]
Explanation:
The expression part adds one to the outcome of the loop. Therefore, the final numbers in the list are changed. We can use a lot of other expressions instead of a simple addition operation. The expression part thus can be very useful to write better code.
FAQs about line comprehension
1. Can line comprehension be done without the condition part?
Solution: Yes, line comprehension does not require condition part in all cases. Line comprehension can be done without it but in most cases it is useful. For Example:
Code:
#list comprehension without condition part
num = [x for x in range(5)]
#printing the list
print(num)
Output:
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
2. Why should we use list comprehension?
Solution: There are numerous advantages of using a list:
1) Less coding: We need to write a single line of code instead of 2-4 lines.
2) Save time: Since less code is to be written, it saves a lot of time.
3) Eliminate function use: Sometimes, we require an external function to create a new list. Line comprehension eliminates the need to create such functions.
3. Are there any disadvantages of using list comprehension?
Solution: There are no disadvantages as such, but it sometimes makes code hard to read. If something goes wrong, it is hard to detect.