Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to double all the values in a list

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.

like image 679
jane Avatar asked Dec 07 '22 06:12

jane


1 Answers

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]
like image 102
Fred Foo Avatar answered Dec 26 '22 19:12

Fred Foo