Rotating lists?

Raymond Hettinger vze4rx4y at verizon.net
Fri Sep 17 06:06:24 CEST 2004


[Ivan Voras]> > a = a[1:] + a[0]
> >
> > which doesn't work because there's no __add__ between a list and
> > integer, and:

[Paul Rubin]
> You meant to say
>
>   a = a[1:] + [a[0]]

A better answer is a[1:] + a[:1] which nicely handles lists of length 0 and
length 1 as well as the OP's original example.

The advantage of using slices to extract a single element is that it avoids
IndexErrors for empty lists.  This technique comes up often enough that I
thought it worth pointing out here.

Also worth mentioning is that slicing and concatenation are supported by several
sequence types.  So, this operation can be abstracted to apply to more than just
lists.

It might also be opportune to point out the virtues of writing a few doctests
that would have surfaced the issues immediately.

Of course, Paul already knows this.  This note is for the people who don't.


Raymond Hettinger


def rotate(seq):
    """ Rotate the first element to the end of a sequence.

    Returns a new sequence of the same type.
    The type must support slicing and concatenation.

    >>> rotate(range(5))
    [1, 2, 3, 4, 0]
    >>> rotate(range(1))
    [0]
    >>> rotate(range(0))
    []
    >>> rotate('abc')
    'bca'
    >>> rotate('')
    ''
    >>> rotate(tuple('abc'))
    ('b', 'c', 'a')
    >>> rotate(tuple(''))
    ()
    """

    return seq[1:] + seq[:1]

import doctest
doctest.testmod()





More information about the Python-list mailing list