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,350 points
193 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
• 56,520 points

Related Questions In Python

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 in Python by Trisha
43 views
+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
4,936 views
+1 vote
4 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
594 views
+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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 222 views
+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
• 56,520 points
61 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
• 56,520 points

edited Aug 21, 2018 by Omkar 126 views