[Tutor] Compound if statement question.

Corey Richardson kb1pkl at aim.com
Sun May 1 20:52:38 CEST 2011


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 05/01/2011 02:28 PM, 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”.
> 

Well, think about what that if-statement is doing. It's making sure that
the first three elements of L aren't equal to each other. Due to
python's short-circuit evaluation, it breaks the if after the first one,
because '1' != '4'. The parentheses there are useless.

You might look at [1] to see if there is anything that will count how
many times something appears in a list...

[1] -- http://docs.python.org/tutorial/datastructures.html#more-on-lists

- -- 
Corey Richardson
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.17 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJNvav2AAoJEAFAbo/KNFvpx/IH/iT54cNeVSSJsRQit13Hf91H
y6zy9Cx3pE9Pxf+crK+9tT53C67TxQIdLRcD83fuXF1iEZJYwVlgQv5Py7U7KIy2
X0SU9ScL4xy/b3k8QB+kj7w7wt4Aa0yPhAx6mZI0KXErj6hVjeIljQf6E3irY7K1
Uot5TY5vY6YieKX+Sc/C2Kv3nmPCM2x1TcuwzX+zIGFBNEuGDb1jNdTR8LkVG+nb
WqBPEtO5sEy9/5NULtExSgS80xUT/fLCRc6gpf5yQBIi/xm+lOBTx1hUCgYfrsLp
gCKOIrXtPaI1bYdxf2tApDUWXVAe5U7tB9z4s9Uz9bV3x8od2w5gsCmxLLJgLHs=
=Sz54
-----END PGP SIGNATURE-----


More information about the Tutor mailing list