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?
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?
Try L = list(map(lambda x: 2**x, range(7)))
once. You were using X
instead of x
.
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
.
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(...)
.
You have a typo. It should be:
# Upper case X refers to 5
list(map(lambda x: 2**x, range(7)))