Table of Contents
ToggleA list comprehension is a concise way to create lists. It is similar to set builder notation in mathematics. It is used to define a list based on an existing iterable object, such as a list, tuple, or string, and apply an expression to each element in the iterable.
The basic syntax of list comprehension is:
new_list = [expression for item in iterable if condition]
Where:
Suppose we want to convert all the letters in the string “hello world” to their uppercase form. Using list comprehension, we iterate through each character, check if it is a letter, and if so, convert it to uppercase, resulting in a list of uppercase letters:
string = "hello world"
uppercase_letters = [char.upper() for char in string if char.isalpha()]
print(uppercase_letters)
Output:
['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']
In Python, lambda is a keyword used to create anonymous functions. We can use list comprehension with lambda by applying the lambda function to each element of an iterable within the comprehension, generating a new list.
original_list = [1, 2, 3, 4, 5]
doubled_list = [(lambda x: x * 2)(x) for x in original_list]
print(doubled_list)
Output:
[2, 4, 6, 8, 10]
We can use nested loops in list comprehension by placing one loop inside another, allowing for concise creation of lists from multiple iterations.
list1=[1,2,3]
list2=[4,5,6]
CombLst=[(x,y) for x in list1 for y in list2]
print (CombLst)
Output:
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Conditionals in Python allow us to filter elements within a list comprehension based on a specified condition.
The following example uses conditionals within a list comprehension to generate a list of even numbers from 1 to 20:
list1=[x for x in range(1,21) if x%2==0]
print (list1)
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
List comprehensions and for loops are both used for iteration, but they differ in terms of syntax and usage.
For Loop Example:
chars=[]
for ch in 'Vista Academy':
if ch not in 'aeiou':
chars.append(ch)
print (chars)
Output:
['V', 's', 't', ' ', 'c', 'd', 'm', 'y']
Using List Comprehension:
chars = [ char for char in 'Vista Academy' if char not in 'aeiou']
print (chars)
Output:
['V', 's', 't', ' ', 'c', 'd', 'm', 'y']
squares = [x*x for x in range(1,11)]
print (squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
