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.
Tuesday, April 01, 2008
Subscribe to:
Posts (Atom)