tags:

views:

164

answers:

4
X = 5
L = list(map(lambda x: 2**X, range(7)))
print (L)

... I'm expecting this to return:

[1, 2, 4, 8, 16, 32, 64]

...instead, it returns:

[32, 32, 32, 32, 32, 32, 32]

What am I doing wrong?

+2  A: 

Try L = list(map(lambda x: 2**x, range(7))) once. You were using X instead of x.

D.Shawley
+8  A: 

Python is case-sensitive, so lambda x: 2**X means: take an argument, call it (lowercase) x, ignore it completely, and return 2 to the power of global variable (uppercase) X.

Alex Martelli
AH! Proves that I'm a real beginner! :P Thanks!
Nimbuz
+5  A: 

Python is case-sensitive. x and X are different variables.

By the way, perhaps an easier way to construct L would be

L=[2**x for x in range(7)]

Or, if you'd like to use map and lambda, then

L=map(lambda x: 2**x, range(7))

suffices. map returns a list, so you do not have to wrap the expression in a list(...).

unutbu
A: 

You have a typo. It should be:

# Upper case X refers to 5
list(map(lambda x: 2**x, range(7)))
Vijay Mathew