List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
- expression
- iteration
- condition
a=[ele for ele in range(10)] #0,1,2,3,4,5,6,7,8,9
print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a=[ele*ele for ele in range(10)]
print(a)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
a=[ele*ele for ele in range(10) if ele%2==0]
print(a)
[0, 4, 16, 36, 64]
a=[ele*ele for ele in range(10) if ele%2==1]
print(a)
[1, 9, 25, 49, 81]
========================================
Example:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Output:
['apple', 'banana', 'mango']
========================================
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
newlist = [x for x in fruits if "a" in x]
print(newlist)