0

Take for example the code below with 2 for loops.

for xy in set:
        for name in dict:
            if xy == name:
               print("Yay")

What I'm wondering is, if after the if statement is found to be true, will it keep iterating through 'dict' or will it go back upto the first for loop and move onto the next iteration? I can't believe how long I've been using python and I don't know the answer to such a simple question.

Thanks!

1
  • 1
    Instead of iterating over dict, why not just test if xy in dict:? Commented Jan 29, 2014 at 17:08

3 Answers 3

5

It will continue to iterate in dict. If you want to jump out of the inner loop, use break.

You can also try.

if any(name in dict for name in set):
    print('Yay')
Sign up to request clarification or add additional context in comments.

1 Comment

A very nice solution. I'm not sure how usable it'll be for me because I actually need to keep both of the ids separate to split them and do other things.
4

It keep iterate through dict.

If you want the loop go back upto first for loop, use break statement:

for xy in set:
    for name in dict:
        if xy == name:
           print("Yay")
           break

As Jacob Krall commented, You don't need to iterate the dictionary object to check whether key(name) exist. Use in operator:

>>> d = {'sam': 'Samuel', 'bob': 'Robert'}
>>> 'bob' in d
True
>>> 'tom' in d
False

for xy in set:
    if name in dict:
        print("Yay")

If you want print Yay only once, use set.isdisjoint:

if not set.isdisjoint(dict):
    print("Yay")

BTW, do not use set or dict as variable name. It shadows builtin function set, dict.

Comments

2

It will continue to iterate over dict. If you do not want this behavior try this:

for xy in set:
    for name in dict:
        if xy == name:
           print("Yay")
           break

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.