See
See

Reputation: 81

Python Double Loop

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!

Upvotes: 2

Views: 2191

Answers (2)

arshajii
arshajii

Reputation: 129507

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

Upvotes: 5

alko
alko

Reputation: 48317

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

Upvotes: 3

Related Questions