Tuesday, April 01, 2008

Python note: reversing lists

There are two ways to reverse a list. One way is to modify the original list:

l = [1,2,3]
l.reverse() # l becomes [3,2,1]

The other way is not to modify the original list, but make a copy:

l = [1,2,3]
l[::-1] # l remains

Notes: l[start:end:step] makes a new sequence from l by slicing. For example, l[1:2] makes a new list [2] and l[0:3] makes [1,2,3]. l[:] is often used to make a copy of the whole list l. This is useful when we want to pass the value (not rerence) of l to a new list.

1 comment:

Xi.Cheng said...

It is always a pleasant to pick up the pythonic beads