List Comprehension in Python With Examples
In python List is a collection of data surrounded by brackets i.e. [ ]. For example: list = [1, 3, 'F', 'Bar', 9.8]
. Each elements in the list are separated by comma.
Like list, List Comprehension is also surrounded by brackets i.e. [ ]. But, instead of comma separated list of data inside, it has expression followed by for
loops and if
clauses.
Most basic forms or syntaxes for list comprehension are:
list_name = [expression for value in collection]
#OR
list_name = [expression for value in collection if condition]
#OR
list_name = [expression for value in collection if condition1 and condition2]
#OR
list_name = [expression for value1 in collection1 for value2 in collection2 ]
Here are examples for each of them:
Example 1: List of Cubes Using List Comprehension
cubes = [i**3 for i in range(1,11)]
print(cubes)
Output
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Example 2: List of Cubes of Odd Numbers Using List Comprehension
cubes = [i**3 for i in range(1,11) if i%2==1]
print(cubes)
Output
[1, 27, 125, 343, 729]
Example 3: Movie Name Starting with 'The' and Ending with 'r' Using List Comprehension
# List
movies = ['The Seven Samurai', 'Bonnie and Clyde', 'Reservoir Dogs', 'Airplane', 'Pans Labyrinth', 'Doctor Zhivago', 'The Deer Hunter', 'Close Encounters of the Third Kind', 'Memento','The Godfather','The Wizard of Oz','Citizen Kane','The Shawshank Redemption','Pulp Fiction','Casablanca', 'The Godfather: Part II']
# List Comprehension
themovies = [movie for movie in movies if movie.startswith('The') and movie.endswith('r')]
print(themovies)
Output
['The Deer Hunter', 'The Godfather']
Example 3: Cartesian Product Using List Comprehension
setA = [10, 20, 30]
setB = [15, 25, 35]
product = [(i,j) for i in setA for j in setB]
print(product)
Output
[(10, 15), (10, 25), (10, 35), (20, 15), (20, 25), (20, 35), (30, 15), (30, 25), (30, 35)]