What is lambda?

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: 

Syntax of lambda

lambda arguments : expression

Example: 

Python3




lst = list(map(lambda x: x**2, range(1, 5)))
print(lst)


Output:

[1, 4, 9, 16]

Difference between List comprehension and Lambda in Python

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.

Syntax of list comprehension

List = [expression(i) for i in another_list if filter(i)]

Example: 

Python3




lst = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(lst)


Output:

[1, 9, 25, 49, 81]

In the above example,

  • x ** 2 is the expression.
  • range (1, 11) is an input sequence or another list.
  • x is the variable.
  • if x % 2 == 1 is predicate part.

Similar Reads

What is lambda?

...

The difference between Lambda and List Comprehension

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:...

Graphical representation of list comprehension vs lambda + filter

...