python - How to double all the values in a list -


n = [3, 5, 7]  def double(lst):     x in lst:         x *= 2         print x     return lst  print double(n) 

why doesn't return n = [6, 10, 14]?

there should better solution looks [x *=2 x in lst] doesn't work either.

any other tips for-loops , lists appreciated.

why doesn't return n = [6, 10, 14]?

because n, or lst called inside double, never modified. x *= 2 equivalent x = x * 2 numbers x, , re-binds name x without changing object references.

to see this, modify double follows:

def double(lst):     i, x in enumerate(lst):         x *= 2         print("x = %s" % x)         print("lst[%d] = %s" % (i, lst[i])) 

to change list of numbers in-place, have reassign elements:

def double(lst):     in xrange(len(lst)):         lst[i] *= 2 

if don't want modify in-place, use comprehension:

def double(lst):     return [x * 2 x in lst] 

Comments