[Tutor] for loop

Alan Gauld alan.gauld at freenet.co.uk
Tue Apr 19 09:37:08 CEST 2005

> *Ron A*  /Wed Jan  7 18:41:15 EST 2004/
> I'm experimenting and would like 'yes' to be printed only if 5 is
not in
> the list, but I want to look in each list. This prints out two
> How do I get it to print just one 'yes'?
> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
> for num in x:
>     if 5 in num:
>         break
>     else:
>         print 'yes'

There are several ways to do this but the two  that I would suggest

for num in x:
    if 5 in num:
       found = True

if found: print 'yes'

Or using list comprehensions(Which you probably haven't discovered

resp = ['yes' for num in x if 5 in num]
if resp: print resp[0]


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list