List Comprehension in Python
What is list comprehension? It's a concise way to create lists in Python.
What is it used for? It allows you to write an expression with clauses and conditions that automatically generates a list with specific values. List comprehension can perform the task of multiple instructions and lines of code in a single expression.
How List Comprehension Works
The expression must be written inside square brackets [ ] because the output is a list of elements.
[ expression ]
The expression can include commands, clauses, and mathematical calculations.
A Practical Example
Let's say I want to create a list of numbers from 0 to 9.
my_list = [i for i in range(10)]
The expression [i for i in range(10)] assigns the value i to each element over ten iterations.
The list is automatically created with the following contents:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If I wanted to achieve the same result with traditional programming, I would need to write three lines of code:
my_list=[]
for x in range(10):
my_list.append(x)
So, using list comprehension is much quicker.
Practical Examples of List Comprehension
Here are some practical examples to better understand how list comprehension works in Python.
Example 1
To create a list of the squares of numbers from 0 to 9, you write:
my_list = [x**2 for x in range(10)]
The result is a list with the following elements:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example 2
To read elements from a list, multiply them by a value, and assign the result to another list, you write:
list1 = [3, 4, 5]
list2 = [item * 2 for item in list1]
In this case, the expression reads each element (item) in list1, multiplies it by 2, and assigns the product to list2.
The expression creates list2 with the following elements:
[6, 8, 10]
Example 3
In this expression, I add a condition to the calculation.
list1 = [3, 4, 5]
list3 = [item * 2 for item in list1 if item % 2 == 0]
Here, I've added an if condition "item % 2 == 0" to the expression.
The expression performs the calculation (item * 2) only if the element (item) from list1 is divisible by two without a remainder (item % 2 == 0), meaning it’s an even number.
The expression creates list3 with the following elements:
[8]
It created only one element because list1 consists of [3, 4, 5] and only one is even (4).
So, 4 * 2 equals 8.
Example 4
In this expression, I extract the initial letter of each word in list1 and assign it to list2.
list1 = ["Rome", "Naples", "Florence"]
list2 = [word[0] for word in list1]
The expression creates list2 with the following elements:
['R', 'N', 'F']
Example 5
In this example, I convert all elements in a list to uppercase:
list1 = ["Rome", "Naples", "Florence"]
list2 = [x.upper() for x in list1]
The final result in list2 is:
['ROME', 'NAPLES', 'FLORENCE']
To convert them to lowercase, you just need to use the opposite function (lower):
list2 = [x.lower() for x in list1]
Now the content of list2 is:
['rome', 'naples', 'florence']
Example 6
In this expression, I want to select only the numeric characters from a string:
string = "Python Guide 2018"
list1 = [x for x in string if x.isdigit()]
The final result in list1 is:
['2', '0', '1', '8']
To select only the alphabetic characters, you need to use the isalpha() method:
list1 = [x for x in string if x.isalpha()]
Now the content of list1 is:
['P', 'y', 't', 'h', 'o', 'n', 'G', 'u', 'i', 'd', 'e']
Example 7
Python list comprehension also allows you to search within a file.
I have a file "test.txt" with three records:
Python Course in Rome
Cobol Course in Milan
C Course in Verona
To select all records in the file that contain the term "Python," you write:
fh = open("test.txt", "r")
list1 = [line for line in fh if "Python" in line]
The expression selects only one record and adds it to the list:
Python Course in Rome
And so on.