2
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?

3
  • You probably don't need a while loop: list(enumerate(my_list*2, 1)) Commented Nov 22, 2016 at 17:57
  • Your loop will never run since you start i at 10 and loop only while i is less than 10. I am not sure why you thought that would work. Start i where you want to start (1 in this case). You have other problems but those will have clear solutions when you get to them. Commented Nov 22, 2016 at 17:58
  • 2
    You start with i = 10, therefore you will never enter the while loop. Commented Nov 22, 2016 at 18:00

4 Answers 4

3
my_list=[1,2,3,4,5]
for index, item in enumerate(my_list*2, start = 1):
    print index,item
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
for x in range(10):
    print(x+1,list[x%len(list)])

This code is unchecked and you may need to modify it a bit.

Comments

0

You can try this easier way :

    my_list = [1,2,3,4,5]
    newList = (enumerate(my_list*2))
    for num in newList:
        print(num)

Output:

(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 1)
(6, 2)
(7, 3)
(8, 4)
(9, 5)

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.