[Tutor] iterating over a sequence question..

Luke Paireepinart rabidpoobear at gmail.com
Sun Jun 17 11:13:47 CEST 2007

Alan Gauld wrote:
> "Iyer" <maseriyer at yahoo.com> wrote
>> Any pythonic way to iterate over a sequence, while iterating 
>> over another shorter sequence continously 
The first thing that occurred to me was just to use a modulus to index 
into the second, shorter list.
 >>> l = [1,2,3,4,5]
 >>> t = ('r','g','b')
 >>> for i in range(len(l)):
    print (l[i], t[i%len(t)])

which results in
(1, 'r')
(2, 'g')
(3, 'b')
(4, 'r')
(5, 'g')

not exactly Pythonic either, and you are assuming that l is longer than 
t (it is easy to account for opposite case as well.)

a more expanded version that accounts for either list being the longer 
one, or both being the same length, would be:

 >>> if len(t) > len(l): x = len(t)
else: x = len(l)
 >>> print [(l[i%len(l)],t[i%len(t)]) for i in range(x)]
[(1, 'r'), (2, 'g'), (3, 'b'), (4, 'r'), (5, 'g')]


More information about the Tutor mailing list