List comprehension: 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 :
- Output expression,
- Input sequence,
- A variable representing a member of the input sequence and
- An optional predicate part.
List = [expression(i) for i in another_list if filter(i)]
[1, 9, 25, 49, 81]
In the above example,
- x ** 2 is the expression.
- range (1, 11) is input sequence or another list.
- x is the variable.
- if x % 2 == 1 is predicate part.
Lambda: In Python, 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 : expression
[1, 4, 9, 16]
The difference between Lambdas and List Comprehension
List Comprehension is used to create lists, Lambdas are functions that can process like other functions and thus return values or list.
[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]
- Python List Comprehension | Segregate 0's and 1's in an array list
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Python Program to Sort the list according to the column using lambda
- Lambda expression in Python to rearrange positive and negative numbers
- Lambda and filter in Python Examples
- Map function and Lambda expression in Python to replace characters
- Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
- Intersection of two arrays in Python ( Lambda expression and filter function )
- Python List Comprehension and Slicing
- K’th Non-repeating Character in Python using List Comprehension and OrderedDict
- List comprehension and ord() in Python to remove all characters other than alphabets
- Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
- Python lambda (Anonymous Functions) | filter, map, reduce
- Overuse of lambda expressions in Python
- Python | Find fibonacci series upto n using lambda
- Python | sympy.Lambda() method
- Python lambda
- Python Lambda with underscore as an argument
- Nested Lambda Function in Python
- Move all zeroes to end of array using List Comprehension in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.