Comprehension
- A compact way of creating a Python data structure from iterators.
- With comprehensions, you can combine loops and conditional tests with a less verbose syntax.
- Comprehension is considered more Pythonic and often useful in a variety of scenarios.
Basic Example
Suppose you want to create a list of all integer square numbers from 0 to 4. You could build that list by appending one item at a time to an empty list:
Using range() function, the above can be done:
alist = []
for x in range(5):
alist.append(x*x)
print(alist)
# Prints [0, 1, 4, 9, 16]
The following examples are self explanatory
# lambda functions
#ex 1
print(50*'_','Iteration using normal for loop')
alist = []
for x in range(5):
alist.append(x*x)
print(alist)
# Prints [0, 1, 4, 9, 16]
#ex 2 Single line Comprehensive code
print(50*'_','Iteration using Single line code')
alist= [i*i for i in range(0,5)]
print(alist)
#Prints [0, 1, 4, 9, 16]
# ex 3 Please note the print values using lambda alone , def() and lambda and map
def square(i):
return i * i
avalue = lambda x: x * x
print(50*',','using lambda and def() ')
print(avalue(5))
# Prints 25
print(square(5))
#Prints 25
#ex4 using lambda and map function
print(50*'-','using lambda & map ')
alist = list(map(lambda i: i*i, [i for i in range(1,6)]))
print(alist)
#Prints [1, 4, 9, 16, 25]
#ex5 using lambda and filter function
print(50*'-','using lambda & filter ')
ilist = [1,2,3,4,5,7,8,9,10]
flist = filter (lambda x: x > 3, ilist)
print(list(flist))
#Prints [4, 5, 7, 8, 9, 10]
#ex6 lambda and reduce function
print(50*'-','using lambda & reduce ')
# importing functools for reduce()
import functools
# initializing list
ilist = [1, 2, 3, 4, 5]
# to compute product of the list
print("The product of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a * b, ilist))
# Prints:The product of the list elements is : 120
# to compute maximum element from list
print("The maximum element value in the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, ilist))
# Prints The maximum element value in the list is : 5
__________________________________________________ Iteration using normal for loop
[0, 1, 4, 9, 16]
__________________________________________________ Iteration using Single line code
[0, 1, 4, 9, 16]
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, using lambda and def()
25
25
-------------------------------------------------- using lambda & map
[1, 4, 9, 16, 25]
-------------------------------------------------- using lambda & filter
[4, 5, 7, 8, 9, 10]
-------------------------------------------------- using lambda & reduce
The product of the list elements is : 120
The maximum element value in the list is : 5
Ex 4,5,6 explains the lambda function usage.
Happy Learning, 👨👩👫