[Tutor] iterating over a sequence question..

Reed O'Brien reed at reedobrien.com
Sun Jun 17 16:59:22 CEST 2007


On Jun 17, 2007, at 3:44 AM, John Fouhy wrote:

> 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.
>

+1 for John's solution

usage:
 >>> [x for x in itertools.izip(lst, itertools.cycle(t)]
 >>> [(1, 'r'), (2, 'g'), (3, 'b'), (5, 'r')]




More information about the Tutor mailing list