Modifying values in a list

Paul McGuire ptmcg at austin.rr.com
Thu Dec 29 14:25:28 EST 2005


As others have already posted, changing the value of 'value' has
nothing to do with the list variable 'numbers'.  To modify the list in
place, you need to access its members by index.  The following code
does this:

numbers = [1,2,3]
for i in range(len(numbers)):
    numbers[i] *= 2
print numbers

But this is how a C or Java programmer would approach this task, and is
not very Pythonic.

A bit better is to use enumerate (avoids the ugly range(len(blah))
looping):

numbers = [1,2,3]
for i,val in enumerate(numbers):
    numbers[i] = val*2

This also modifies the list in place, so that if you are modifying a
very long (and I mean really quite long - long enough to question why
you are doing this in the first place) list, then this approach avoids
making two lists, one with the old value and one with the new.

But the most Pythonic is to use one of the list comprehension forms
already posted, such as:

numbers = [ x*2 for x in numbers ]

-- Paul




More information about the Python-list mailing list