[Tutor] Compound if statement question.

Steven D'Aprano steve at pearwood.info
Mon May 2 02:14:16 CEST 2011


Greg Christian wrote:
> Is there a way to write an if statement that will pick up duplicates (two ‘1’s):
> 
> L = ['1', '4', '1']
> if (L[0]) != (L[1]) != (L[2]):
>     print "THEY ARE NOT EQUAL"
> else:
>     print "THEY ARE EQUAL"
> 
> When I run this code, it prints “THEY ARE NOT EQUAL” when it should print the else “THEY ARE EQUAL”.

You don't need to put brackets ("parentheses" for any Americans reading) 
around each term. That just adds noise to the code and makes it harder 
to read.

Your test says:

L[0] != L[1] != L[2]

which evaluates to:

'1' != '4' != '1'

which is obviously correct, they are *not* ALL equal. Python comparisons 
chain: the above is equivalent to the longer:

'1' != '4' and '4' != '1'

which is clearly true.


The test you probably want is:

if L[0] == L[1] or L[0] == L[2]:
     print "THEY ARE EQUAL"


For longer lists, this might be better:


if any(L[0] == x for x in L[1:]):
     print "first item equals some other item"


or easier to write:

if L.count(L[0]) > 1:
     print "first item duplicate detected"




-- 
Steven


More information about the Tutor mailing list