Possible Duplicate:
String comparison in Python: is vs. ==
algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm is "first")
I’m running it from the command line with the argument first, so why does that code output:
first
False
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
From the Python documentation:
This means it doesn’t check if the values are the same, but rather checks if they are in the same memory location. For example:
Note the different memory locations:
But since
s3is equal tos1, the memory locations are the same:When you use the
isstatement:But if you use the equality operator:
Edit: just to be confusing, there is an optimisation (in CPython anyway, I’m not sure if it exists in other implementations) which allows short strings to be compared with
is:Obviously, this is not something you want to rely on. Use the appropriate statement for the job –
isif you want to compare identities, and==if you want to compare values.