2

is it possible to for loop 2 lists with another size with the smallest one "relooping"?

example:

list = [1,2,3,4,5,6,7,8,10]
list2 = [a,b]

 newlist = []
 for number, letter in zip(list, list2):
    newlist.append(item)
    newlist.append(item2)

The loop stops at [1a, 2b] cause there are no more items in list2, is it possible for list2 to start over until list1 is empty? ie: newlist = [1a,2b,3a,4b,5a,6b] etc?

thkx!

See
  • 81
  • 1
  • 11
  • 1
    Will the length of the second list be a factor of the first? That is, will it be repeated a whole number of times? – aganders3 Jan 10 '14 at 15:47
  • @AshwiniChaudhary: not quite a dup of that, because that one specifically asks for a way *without* itertools. I'm sure it's a dup of something else, though, I think I've answered this one myself. – DSM Jan 10 '14 at 15:49
  • @DSM This one: [interleaving 2 lists of unequal lengths](http://stackoverflow.com/questions/19883826/interleaving-2-lists-of-unequal-lengths) – Ashwini Chaudhary Jan 10 '14 at 15:50
  • @AshwiniChaudhary: that's not the one I'm thinking of, but `cycle` is fun to use, so it's probably pretty common. :^) – DSM Jan 10 '14 at 15:51

2 Answers2

5
>>> l1 = [1,2,3,4,5,6,7,8,10]
>>> l2 = ['a','b']
>>> 
>>> from itertools import cycle
>>> 
>>> for number, letter in zip(l1, cycle(l2)):
...     print number, letter
... 
1 a
2 b
3 a
4 b
5 a
6 b
7 a
8 b
10 a

See itertools.cycle.

As an aside, you shouldn't use list as a variable name, since that name is already taken by the built-in function list().

arshajii
  • 127,459
  • 24
  • 238
  • 287
3

Use itertools.cycle:

>>> from itertools import cycle
>>> l1 = [1,2,3,4,5,6,7,8,10]
>>> l2 = ['a','b']
>>> map(''.join, zip(map(str, l1), cycle(l2)))
['1a', '2b', '3a', '4b', '5a', '6b', '7a', '8b', '10a']
alko
  • 46,136
  • 12
  • 94
  • 102