[Tutor] for loop

Lee Cullens leec03273 at mac.com
Tue Apr 19 06:59:43 CEST 2005


Well I was reading too fast (as usual) - you wanted to print 'yes'   
only if 5 is not in a sub list but you want to look in all the sub  
lists and yet print 'yes' only once???

So in long hand lets reverse the logic and make sure we print 'yes'  
only once

 >>> yes = 0
 >>> for num in x:
...   if 5 not in num:
...     if not yes:
...       print 'yes'
...       yes = 1
...
yes



>>
On Apr 19, 2005, at 12:31 AM, Lee Cullens wrote:

>  As you probably have already found out the expression
> >>> print [ e for e in x if 5 in e]
> will produce
> [[8, 4, 5, 6]]
>
> The problem with your original code is that you are printing 'yes' for  
> each sub list until you encounter a sub list with 5 whereupon you  
> break without printing yes.
>
> If you change your test to check for 5 in a sub list and, print yes  
> and break at that point you will get the results you are looking for.
>
> >>> for num in x:
> ...      if 5 in num:
> ...        print "yes"
> ...        break
> ...
> yes
> >>>
>
> Lee C
>
>
>
> On Apr 18, 2005, at 11:51 PM, Ching-Yi Chan wrote:
>
>> *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 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'
>>
>> ---------------------------------------------------------------------- 
>> ----
>>
>> Hi, I read the code and consider for a while, you can try it :
>>
>> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>> print [ e for e in x if 5 in e]
>>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list