![]() |
VOOZH | about |
List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp.
A list comprehension generally consists of these parts :
List = [expression(i) for i in another_list if filter(i)]Example:
Output:
[1, 9, 25, 49, 81]In the above example,
In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. It has the following syntax:
lambda arguments : expressionExample:
Output:
[1, 4, 9, 16]List Comprehension is used to create lists, Lambda is function that can process like other functions and thus return values or lists.
Example:
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
As we can see from the graph that overall list comprehension is much faster than the filter function. The filter is faster for a small list only.
Output: