diff --git a/blog_images/umbrellas.jpg b/blog_images/umbrellas.jpg new file mode 100644 index 000000000..23470d3dc Binary files /dev/null and b/blog_images/umbrellas.jpg differ diff --git a/blog_posts/python-identity-equality.md b/blog_posts/python-identity-equality.md new file mode 100644 index 000000000..baa167eb2 --- /dev/null +++ b/blog_posts/python-identity-equality.md @@ -0,0 +1,45 @@ +--- +title: What is the difference between Python's equality operators? +type: question +tags: python,type,comparison +authors: maciv +cover: blog_images/umbrellas.jpg +excerpt: Python provides two distinct comparison operators for different task. Stop mixing them up using this quick guide. +--- + +Python provides two very similar equality operators used for comparisons: + +- The double equals (`==`), also known as the equality operator +- The `is` keyword, also known as the identity operator + +Although similar to one another, the double equals (`==`) and the `is` keyword are used for different comparison purposes and yield different results. + +The main difference between the two is that the `is` keyword checks for reference equality while the double equals (`==`) operator checks for value equality. In other words, `is` will return `True` if two variables both refer to the same object in memory (aka. identity), whereas the double equals operator will evaluate to `True` if the two objects have the same value. + +Here are some examples to clear up any confusion: + +```python +a = [1, 2, 3] +b = a +c = [x for x in a] + +print([ + a == b, # True + a is b, # True + a == c, # True + a is c # False +]) + +x = 'hi' +y = x +z = 'HI'.lower() + +print([ + x == y, # True + x is y, # True + x == z, # True + x is z # False +]) +``` + +**Image credit:** [cyril mazarin](https://unsplash.com/@cyril_m?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)