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!

4
  • 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? Commented Jan 10, 2014 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. Commented Jan 10, 2014 at 15:49
  • @DSM This one: interleaving 2 lists of unequal lengths Commented Jan 10, 2014 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. :^) Commented Jan 10, 2014 at 15:51

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.