nick m nick m - 3 months ago 7
Python Question

How to switch between loops?

I have a program that generates two lists. I want to print an item from list1 then switch to printing an item from list 2 and then go back to printing from list1 ..etc. However whenever I try it it just prints list1 then list2.

Please help.

Code:

List1 = ['a', 'b' , 'c', 'd', 'e', 'f']

List2 = ['1', '2', '3', '4', '5', '6']

continue = True

while continue == True:
for i in List1:
print i
print '/n'
continue = False

while continue == False:
for i in List2:
print i
print '/n'
continue = True


Output:

a
b
c
d
e
f
1
2
3
4
5
6


Desired output:

a
1
b
2
c
3
d
4
e
5
f
6

Answer

My answer is based around the code for your question. If this is the format you are wanting then use my answer. Otherwise, the other answers are more Pythonic as stated.

Please not that I've renamed "continue" to "switch" as continue is a reserved Python word, producing a syntax error.

List1 = ['a', 'b' , 'c', 'd', 'e', 'f']

List2 = ['1', '2', '3', '4', '5', '6']

switch = True
while True:
    while switch == True:
        for i in List1:
            print(i)
            List1.pop(0)
            switch = False
            break

    while switch == False:
        for i in List2:
            print(i)
            List2.pop(0)
            switch = True
            break

If you set the state of the variable switch then break the loop it will do exactly as you desire.

Due to this loop break I .pop() the 0th index value to ensure the correct output is received.

This code is very inefficient and I am sure you can find other methods of producing your desired output.

Edit: To do this with unequal list lengths you must add switch = False at the end of the while switch == True: loop and vice versa for while switch == False:

Edit 2: This also gives you a solution for switching between loops :)