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)]

and

[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,510 points
2,669 views

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
• 58,020 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, 2020 in Python by MD
• 95,460 points
649 views
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
6,535 views
0 votes
1 answer
+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
35,472 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

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

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,127 views
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
• 58,020 points
1,091 views
+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
• 58,020 points

edited Aug 21, 2018 by Omkar 1,377 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP