LIST COMPREHENSION.
What is list comprehension?
List comprehension is an elegant way to create lists. A python list comprehension consists of expressions enclosed by square brackets.
For example:
x=[]
for i in range (11):
x.append(i)
print(x)
output:- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x=[i for i in range(11)]
print(x)
output:- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Advantages of list comprehension over normal way.
1. More time efficient and space efficient than loops.
2. Requires fewer lines of code.
Working of list comprehension.
x=[(expression to get displayed ) (for loop , for range of elements) (conditions)]
For example:-
x=[i for i in range(1,11) if i%2==0]
print(x)
output:-[2, 4, 6, 8, 10]
Some examples of comprehension.
1. Creating a list of even numbers from 0 to 100.
x=[i for i in range(100) if i%2==0 ]
print(x)
output:-[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
2. Nested list comprehension.
x=[[i for i in range(3)] for j in range(5)]
print(x)
output:-[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
3. Squares of 10 numbers.
x=[i**2 for i in range(1,11)]
print(x)
output:-[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]