Python: Lambda function in List Comprehensions

0 votes

Why is the output of the following two list comprehensions different, even though f and the lambda function are the same ?

f = lambda x: x*x
[f(x) for x in range(10)]


[lambda x: x*x for x in range(10)]

Mind you, both type(f) and type(lambda x: x*x) return the same type.

Aug 27, 2018 in Python by bug_seeker
• 15,400 points

1 answer to this question.

0 votes

The first one create a single lambda function and calls it ten times.

The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:

[(lambda x: x*x)(x) for x in range(10)]

Or better yet:

[x*x for x in range(10)]

answered Aug 27, 2018 by Priyaj
• 57,550 points

Related Questions In Python

0 votes
1 answer

How to create lambda function inside a list in Python?

Hi@akhtar, The lambda statement can appear in places ...READ MORE

answered Jun 25 in Python by MD
• 40,860 points
0 votes
1 answer

Difference between a normal def defined function and lambda function in python?

Have a look at this code: # Python ...READ MORE

answered May 20, 2019 in Python by Trisha
+4 votes
7 answers

Splitting a List into chunks in Python

Here's a generator that yields the chunks ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,177 views
0 votes
0 answers
+4 votes
6 answers
0 votes
1 answer

Creating an empty list in Python

Here is how you can test which ...READ MORE

answered Aug 17, 2018 in Python by Priyaj
• 57,550 points
+1 vote
1 answer

What is the function for Factorial in Python

Easiest way: math.factorial(x) (available in 2.6 and ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 57,550 points

edited Aug 21, 2018 by Omkar 279 views