Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (50.2k points)

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.

1 Answer

0 votes
by (108k points)

The first one produces a single lambda function and then 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)]

Related questions

+8 votes
2 answers
+10 votes
1 answer
0 votes
1 answer
+1 vote
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...