List Comprehension

Python supports a concept called “list comprehensions”. It can be used to construct lists in a very natural, easy way, like a mathematician is used to do. List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce().Usually we write mathematical collection of prime numbers, even and odd numbers in a list and mathematically we represent it as :

S = {x² : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2¹²)
M = {x | x in S and x even}

The same work we can do it by using Python list comprehension:

#List comrehension used for Even numbers
Even = [x for x in range(20) if x%2==0]
power2=[2**i for i in range(20)]
print(Even)
print(power2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288]
words='hello this is a document on list comrehension'.split()
stuff = [[w.upper(), w.lower(), len(w)] for w in words]
[['HELLO', 'hello', 5],
 ['THIS', 'this', 4],
 ['IS', 'is', 2],
 ['A', 'a', 1],
 ['DOCUMENT', 'document', 8],
 ['ON', 'on', 2],
 ['LIST', 'list', 4],
 ['COMREHENSION', 'comrehension', 12]]

Leave a Reply