Reversing a Sequence

Question

How do you reverse the elements in a sequence or along one dimensions in an array (like the reverse function in IDL)?

Answer

If the sequence is a list, just use the reverse method:

>>> a = [1, 2, -6, 4, -8]
>>> a.reverse()
>>> a
[-8, 4, -6, 2, 1]

Tuples, of course, are immutable, so they can't be reversed in place like lists.

For a Numeric array, there isn't a reverse method. Instead you do this through extended indices:

>>> a = Numeric.array([1, 2, -6, 4, -8])
>>> a = a[::-1]
>>> a
array([-8, 4, -6, 2, 1])

For a 2-D array:

>>> a = Numeric.array([[1, 2, -6, 4, -8], [-2, 3, 7, 9, -1]])
array([[ 1, 2, -6, 4, -8],
       [-2, 3,  7, 9, -1]])
>>> b = a[:,::-1]
>>> b
array([[-8, 4, -6, 2,  1],
       [-1, 9,  7, 3, -2]])
>>> c = a[::-1,:]
>>> c
array([[-2, 3,  7, 9, -1],
       [ 1, 2, -6, 4, -8]])

The syntax of extended indexing is start:stop:stride. When the start and stop values are left out, the interpreter automatically specifies the entire sequence. A stride of -1 decrements element index by 1. Remember in Python sequence indexing the start index is included while the stop index is excluded. Extended array indexing is supported on lists and tuples starting with Python 2.3.

Martelli (2003) gives a comprehensive and concise discussion of sequence slicing (pp. 47, 207-308).

Return to the Tips and Examples index page.

Updated: November 10, 2003 by Johnny Lin <email address>. License.