n = [3, 5, 7]
def double(lst):
for x in lst:
x *= 2
print x
return lst
print double(n)
Why doesn't this return n = [6, 10, 14]
?
There should also be a better solution that looks something like [x *=2 for x in lst]
but it doesn't work either.
Any other tips about for-loops and lists would be much appreciated.
Why doesn't this return
n = [6, 10, 14]
?
Because n
, or lst
as it is called inside double
, is never modified. x *= 2
is equivalent to x = x * 2
for numbers x
, and that only re-binds the name x
without changing the object it references.
To see this, modify double
as follows:
def double(lst):
for i, x in enumerate(lst):
x *= 2
print("x = %s" % x)
print("lst[%d] = %s" % (i, lst[i]))
To change a list of numbers in-place, you have to reassign its elements:
def double(lst):
for i in xrange(len(lst)):
lst[i] *= 2
If you don't want to modify it in-place, use a comprehension:
def double(lst):
return [x * 2 for x in lst]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With