On Sat, Nov 1, 2008 at 5:40 PM, Sander Sweers <[EMAIL PROTECTED]> 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 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor