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!
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')
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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.