salim ep salim ep - 14 days ago 6
Python Question

while loop using python list

my_list=[1,2,3,4,5]





i = 10
while i < 10:
print i ,my_list
i = i +1


My desired output:

1,1
2,2
3,3
4,4
5,5
6,1
7,2
8,3
9,4
10,5


How can I achieve this?

Answer

Your task is what itertools.cycle is built for (from Python's standard library):

In [5]: from itertools import cycle

In [6]: for i, j in zip(xrange(1, 11), cycle(my_list)):
   ...:     print i, j
   ...:
1 1
2 2
3 3
4 4
5 5
6 1
7 2
8 3
9 4
10 5

In [7]: for i, j in zip(xrange(12), cycle(my_list)):
   ...:     print i, j
   ...:
0 1
1 2
2 3
3 4
4 5
5 1
6 2
7 3
8 4
9 5
10 1
11 2