[Tutor] for loop

Daniel Ehrenberg littledanehren at yahoo.com
Wed Jan 7 22:01:24 EST 2004


Lloyd Kvam wrote:
> Ron A wrote:
> 
> > 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 yeses.
> > 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'    
> > 
> This code prints yes until it finds a num list that
> contains 5.
> 
> To stop printing yes after the first time, simply
> break after printing
> yes.  However, this is equivalent to simply checking
> the first element
> of x.  You no longer need the loop.  So now the
> equivalent code is:
> 
> if 5 not in x[0]:
> 	print "yes"
> 
> -- 
> Lloyd Kvam

Are you sure that's what he intended to do? Your code
checks only the first list in x, but I think he wanted
to check them all. I would impliment it like this
instead:

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
contains5 = False

for num in x:
    if 5 in x:
        contains5 = True
        break

if contains5: print 'yes'

You still need to loop through x to access each list.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus



More information about the Tutor mailing list