1
a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry', '21', 'cookies']]
for i in range(len(a)):
    if (a[i][1] == '20' or a[i][1] == '26'):
        print 'yes'
    else:
        print 'Not found'

This output's Not found three times. If the output of the every iteration of the if loop is the same, I want it to iterate over the entire list and then print Not found only once.

If I change a[i][1] == '25' and the output becomes:

yes
Not found
Not found

I want to print yes but not Not found.

1 Answer 1

2

may be you're looking for for-else loop.

and as @Burhan Khalid suggested use for i in a instead if range(len(a)):

a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry', '21', 'cookies']]
for i in a:
    if (i[1] == '25' or i[1] == '26'):
        print 'yes'
else:
    print 'Not found'

output:

yes
Not found

Or may be you're looking for any():

In [200]: if any((i[1]=='25' or i[1]=='26') for i in a):
    print 'yes'
else:    
    print 'not Found'
   .....: 


yes

In [204]: if any((i[1]=='20' or i[1]=='26') for i in a):
    print 'yes'
else:    
    print 'not Found'
   .....: 


not Found
Sign up to request clarification or add additional context in comments.

4 Comments

range(len(a)) can be better setup as for i in a:, then if i[1] == '25 or i[1] == '26':
Thanks! It solves the first problem. But it still print Not found once for the second problem. How do I get it to print only yes for positive matches and nothing for negative matches?
print nothing for the negative matches , then why do you want to print Not Found?
@koogee see my edited answer may be that is what you were looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.