[Tutor] Help with a loop

Kent Johnson kent37 at tds.net
Tue Mar 18 17:06:37 CET 2008


PyProg PyProg wrote:
> Hello,
> 
> I have a little problem, I have two lists:
> 
>>>> a=[1, 2, 3, 4, 5, 6]
>>>> b=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
> 
> ... and I want to obtain:
> 
>>>> [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g',
> 1), ('h', 2), ('i', 3), ('j', 4)]
> 
> I want to obtain that with a comprehension-list.
> 
> Lists can have dimension completely different.

Here is one way using itertools.cycle() to repeat elements of a. This 
will return a list the same length as b, with elements of a repeated as 
needed:
In [140]: from itertools import cycle
In [141]: zip(b, cycle(a))
Out[141]:
[('a', 1),
  ('b', 2),
  ('c', 3),
  ('d', 4),
  ('e', 5),
  ('f', 6),
  ('g', 1),
  ('h', 2),
  ('i', 3),
  ('j', 4)]

If b might sometimes be the shorter list you will have to work a little 
harder, perhaps cycle both lists and take the first max(len(a), len(b)) 
elements:
In [142]: from itertools import cycle, islice, izip
In [143]: list(islice(izip(cycle(b), cycle(a)), max(len(a), len(b))))
Out[143]:
[('a', 1),
  ('b', 2),
  ('c', 3),
  ('d', 4),
  ('e', 5),
  ('f', 6),
  ('g', 1),
  ('h', 2),
  ('i', 3),
  ('j', 4)]


Kent


More information about the Tutor mailing list