0

This seems quite simple but I can't get it to work. I'm using Python 3.

I have a nested for loop

for x in list:
    ch_id_dic[i]='channel_id'
    ch_id_dic2= dict((v,k) for k,v in ch_id_dic.items())
    for y in list_2:
        ch_id_dic[j]='description'
        ch_id_dic2= dict((v,k) for k,v in ch_id_dic.items())
        break

After the break statment it goes through the second element of list but then in the nested for loop it goes to the first element again. I want it to go to the second.

Can someone please help me?

Thanks...

James
  • 32,991
  • 4
  • 47
  • 70
Paul
  • 57
  • 2
  • 9
  • 3
    It sounds like you want to iterate through both lists in lockstep. Maybe using the [`zip`](https://docs.python.org/3/library/functions.html#zip) function: `for x, y in zip(list1, list2)` – Patrick Haugh Dec 15 '17 at 01:06
  • Ah, I see. Didn't notice that the flag automatically made a comment. Thanks for feedback, Patrick. – Thomas Fauskanger Dec 15 '17 at 01:08
  • Using the zip function worked! Thanks! – Paul Dec 15 '17 at 01:10
  • 2
    Possible duplicate of [How to break out of multiple loops in Python?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python) – Brown Bear Dec 15 '17 at 11:07
  • @BearBrown, if I understand it correctly, the goal is not to break out of both loops.. – Bart Dec 15 '17 at 13:18

2 Answers2

1

Note that I have made this a CW post to mark it as answered. I take no credit for this answer and give it all to Patrick Haugh, who answered in comments.

Use zip.

You need to iterate through both lists at the same time. The zip(list1,list2) function takes two lists of equal size and turns them into a single list by doing something like [(list1[index],list2[index]) for index in range(len(list1))].

Jakob Lovern
  • 1,301
  • 7
  • 24
0

break statements end the current loop. In your case, as you noticed, it stops the nested loop and continues with the next iteration of the external loop.

It sounds like you are trying to keep the index of the outer loop to match the inner, so track the index of the outer loop with the enumerate function.

for idx, x in enuerate(list):
    ch_id_dic[i] = 'channel_id'
    ch_id_dic2 = dict((v,k) for k,v in ch_id_dic.items())
    for y in range(idx, len(list_2)):
        ch_id_dic[j] = 'description'
        ch_id_dic2 = dict((v,k) for k,v in ch_id_dic.items())
        break

If you need to use the old value of y at some point, just use list_2[y].

iamttc
  • 1
  • 1