[Tutor] iterating over a sequence question..
John Fouhy
john at fouhy.net
Sun Jun 17 09:44:24 CEST 2007
On 17/06/07, Iyer <maseriyer at yahoo.com> wrote:
>
> say, if I have a list l = [1,2,3,5]
>
> and another tuple t = ('r', 'g', 'b')
>
> Suppose I iterate over list l, and t at the same time, if I use the zip
> function as in zip(l,t) , I will not be able to cover elements 3 and 5 in
> list l
>
> >>> l = [1,2,3,5]
> >>> t = ('r', 'g', 'b')
> >>> for i in zip(l,t):
> ... print i
> ...
> (1, 'r')
> (2, 'g')
> (3, 'b')
>
> is there an elegant way in python to print all the elements in l, while
> looping over list t, if len(t) != len(l) as to get the output:
>
> (1, 'r')
> (2, 'g')
> (3, 'b')
> (5, 'r')
Check out the itertools module. I don't have the ability to test this
right now, but try something like:
import itertools
lst = [1,2,3,5]
t = ('r', 'g', 'b')
itertools.izip(lst, itertools.cycle(t))
--
John.
More information about the Tutor
mailing list