Python List Comprehension: Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.
Advantages of List Comprehension in Python:
- Time Efficient than loop
- Space Efficient than loop
- Needs fewer lines of code.
The syntax for list comprehension in Python is as follows:
newList = [ expression(element) for element in oldList if condition]
Python List Comprehension with examples:
Read and practice the following example to become familiar with the python list comprehension
List Comprehension example 1:
a = [8,3,1,5,3,7]
b = [x for x in a if x > 5]
print(b)
OUTPUT: [8, 7]
List Comprehension example 2:
a = [8,2,6,1,9]
b = [x*2 for x in a if x > 5]
print(b)
OUTPUT: [16, 12, 18]
List Comprehension example 3:
data = ['Car','Dhee','Eagle','cup','Tall','Ted']
new_data = [name for name in data if name.lower().startswith('c')]
print(new_data)
OUTPUT: ['Car', 'cup']
List Comprehension example 4:
data = [[1,2,3],[4,5,2],[3,2,6]]
max_data = [max(x) for x in data]
print(max_data)
OUTPUT: [3, 5, 6]
List Comprehension example 5:
names = ['Ch','Dh','Eh','cb','Tb','Td','Chb','Tdb']
new_names = [name for name in names if
name.lower().endswith('b') and len(name) > 2]
print(new_names)
OUTPUT: ['Dheeb', 'cupb']
List Comprehension example 6:
data= ['Car','cheeb','Eagle','cup','cTall','Tedb']
new_data = [name for name in names if name.endswith('b') | name.startswith('c')]
print(new_data)
OUTPUT: ['cheeb', 'cup', 'cTall', 'Tedb']
List Comprehension example 7:
data= [["a", "g"], [0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
new_data= [y for x in data if len(x)>3 for y in x]
print(new_data)
OUTPUT: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
List Comprehension example 8:
data = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
new_data = [y for x in data for y in x]
print(new_data)
OUTPUT: [1, 2, 3, 4, 5, 6, 7, 8, 9]
List Comprehension example 9:
data = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'],
['Uranus', 'Neptune', 'Pluto']]
new_data = [y for x in data for y in x if len(y)>4]
print(new_data)
OUTPUT: ['Mercury','Venus','Earth','Jupiter','Saturn','Uranus','Neptune','Pluto']
List Comprehension example 10:
data= [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto', "Mars55"]]
new_data = [y.upper() for x in data if len(x) == 3 for y in x if y.startswith('M')]
print(new_data)
OUTPUT: ['MERCURY', 'MARS']
I appreciate the reading. Please do not hesitate to give me your comments.
Leave a comment