[Tutor] Checking in lists

Alan Gauld alan.gauld at freenet.co.uk
Wed Apr 26 20:45:21 CEST 2006


> Basically it's not evaluating it the way you think it is:
>
>Your first example really equates to:
>
> if (1 or 5) in rollList:

Not quite, its doing:

if 1 or 5 in rollList:

We can demonstrate that with:

>>> if 1 or 0 in [6,2,3]: print 'True'
...
True
>>> if (1or 0) in [6,2,3]: print 'True'
...
>>>

Here the first expression evaluates to True and never attempts
the 'in' comparison (which would fail). The second uses your
parenthesis style and evaluates to 1 in [6,2,3] which is False

A minor nit pick.

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld






On 4/26/06, John Connors <oztriking at hotmail.com> wrote:
>
> G'day,
>
> I found something today that has me confused. I'm making a list of 6
> random
> dice rolls and I want to check if any 1's or 5's were rolled. I tried this
> way first and it returns true even if there are no 1's or 5's. I'll use a
> roll of all 2's as an example.
>
> rollList = [2,2,2,2,2,2]
> if 1 or 5 in rollList:
>    print 'yes'
> else:
>    print 'no'
>
> Then I tried this and it works fine.
>
> rollList = [2,2,2,2,2,2]
> if 1 in rollList or 5 in rollList:
>    print 'yes'
> else:
>    print 'no'
>
> It doesn't really matter because the second way does what I want but I
> would
> like to know why the first way doesn't work and if the syntax is wrong why
> doesn't it return an error.
>
> John
>
> PS I apologise if this is a duplicate, hotmail did some kind of spam check
> when I tried to send it, I've waited 30 mins and I don't think it went the
> 1st time so I'll post it again.
>
> _________________________________________________________________
> New year, new job – there's more than 100,00 jobs at SEEK
>
> http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>



More information about the Tutor mailing list