[Tutor] iterating over a sequence question..

Simon Hooper simon at partex.co.uk
Mon Jun 18 14:26:26 CEST 2007


Hi Luke,

* On 17/06/07, Luke Paireepinart wrote:
> 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')]

Being the duffer that I am, I'm very pleased with myself that I came up
with a similar solution (albeit as a function rather than a list
comprehension) :)

You do not need the if statement either,

print [(l[i%len(l)],t[i%len(t)]) for i in range(max(len(l), len(t)))]

Regards

Simon.

-- 
Simon Hooper
PARTEX MARKING SYSTEMS UK LTD


More information about the Tutor mailing list