Paul
Paul

Reputation: 57

Nested for loops, break

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

Upvotes: 0

Views: 87

Answers (2)

Jakob Lovern
Jakob Lovern

Reputation: 1341

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

Upvotes: 1

iamttc
iamttc

Reputation: 1

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

Upvotes: 0

Related Questions