[Tutor] Manipulate list in place or append to a new list

Kent Johnson kent37 at tds.net
Sun Nov 2 13:32:29 CET 2008


On Sat, Nov 1, 2008 at 5:40 PM, Sander Sweers <sander.sweers at gmail.com> wrote:
> Hi,
>
> What is the better way to process data in a list? Make the changes in
> place, for example
>
> somelist = [1,2,3,4]
>
> for x in range(len(somelist)):
>    somelist[x] = somelist[x] + 1
>
> Or would making a new list like
>
> somelist = [1,2,3,4]
> newlist = []
>
> for x in somelist:
>    newlist.append(x + 1)
>
> Or is there another way of doing this kind of things. Pointers to
> online resources are most welcome :-)

Use a list comprehension:
somelist = [ x+1 for x in somelist ]

Note that this creates a new list, replacing the one that was in
somelist. If you need to actually modify somelist in place (rare) then
use
somelist[:] =  [ x+1 for x in somelist ]

which creates a new list, then replaces the *contents* of somelist
with the contents of the new list.

If you don't understand how these are different, this might help:
http://personalpages.tds.net/~kent37/kk/00012.html

Kent


More information about the Tutor mailing list