[Tutor] for loop

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Jan 8 02:41:49 EST 2004


> 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:

I couldn't quite work out what the original req was.
But here are another 2 options:

> 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'

# needs python 2.3, lower versions substitute 1 for True
x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
if True in [ 5 in L for L in x]:
   print 'Yes'

Or if you prefer:

# you don't need fthe len() call but I think it 
# makes the intent clearer
x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
if len(filter(lambda L:5 in L, x)) > 0:
   print 'Yes'

Alan G.




More information about the Tutor mailing list