List Comprehensions and Lambda
Lambda Expressions are nothing but shorthand representations of Python functions. Using list comprehensions with lambda creates an efficient combination. Let us look at the below examples:
In this example, we are inserting numbers from 10 to 50 in the list and printing it.
Python
# using lambda to print table of 10 numbers = [] for i in range ( 1 , 6 ): numbers.append(i * 10 ) print (numbers) |
Output
[10, 20, 30, 40, 50]
Here, we have used for loop to print a table of 10.
Python
numbers = [i * 10 for i in range ( 1 , 6 )] print (numbers) |
Output
[10, 20, 30, 40, 50]
Now here, we have used only list comprehension to display a table of 10.
Python
# using lambda to print table of 10 numbers = list ( map ( lambda i: i * 10 , [i for i in range ( 1 , 6 )])) print (numbers) |
Output
[10, 20, 30, 40, 50]
Finally, we use lambda + list comprehension to display the table of 10. This combination is very useful to get efficient solutions in fewer lines of code for complex problems.
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]