[Tutor] iterating over a sequence question..

Alan Gauld alan.gauld at btinternet.com
Sun Jun 17 09:55:08 CEST 2007


"Iyer" <maseriyer at yahoo.com> wrote

> Any pythonic way to iterate over a sequence, while iterating 
> over another shorter sequence continously 

I don;t know how pythonic it is, but I'd do it thus:

>>> a = (1, 2, 3, 4)
>>> b = ('a', 'b', 'c')
>>> n = len(a)/len(b) + 1
>>> t = map(None,a,b*n)[:len(a)]
>>> t
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'a')]
>>> for x,y in t:
...     print x,y
...     
1 a
2 b
3 c
4 a


I suspect you could use a list comp too but map seemed easier.
And of course you could compress it into less lines:

>>> for x,y in map(None,a,b*(len(a)/len(b)+1))[:len(a)]:
...     print x,y

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list