"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Skills:
Python for Data80%
Key Takeaways
Understanding the difference between 'is' and '==' operators in Python
Full Transcript
hey what's up folks it's Dan Bader here and it's time for another python video so I'm doing this new series of videos uh with little python tidbits you know really cool features in Python that you can apply in your own code in your day-to-day work and that are just going to give you a deeper understanding of python and I'm I'm calling them python tricks so this is a new video series I'm starting and um Shameless plug I'm also working on a book under the same name which is going to be almost like a a a buffet of really awesome and cool features in Python that you might not have heard about or you know that you've always been curious about uh about how they might work so I'm actually working on this book in uh In Like An Early Access or like beta mode so you can get updates as they come out and you can get in for a cheaper price and if you're interested I'll I'll put the link into the video description below all right so in this episode of python tricks I want to talk about the difference between the is operator and the equals equals operator because I know that um there this is often a point of confusion for python developers and um I've been trying to come up with you know an example that really boils it down um to to like a minimal example necessary to understand this distinction and I think I got a pretty good shot at this so so bear with me so at the end of the video you're going to know the difference between is and equals equals and you're going to know when to apply them so the key thing here is that there's a difference between two things being identical or two objects being identical and them being equal like there's a semantic difference there's a difference in meaning and so for example when I grew up our neighbors had uh twin cats so there were two cats that looked pretty much exactly the same but of course they were they were two different cats I mean they were not you wouldn't say like oh that's the same cat right that would be crazy because there's two of them and I'm going to keep stretching that analogy even thinner so bear with me right so there are two different cats and uh they're two different entities but they look the same like you could say oh they're they're equal but uh really what this example shows is that there's a difference between something being two things being equal and two things being identical and that difference is really important if you want to understand and the difference between is and the equals equals operator so let's start with the equals equals operator first so this guy here it Compares by checking for equality so if these cats were python objects and we compared them with the equals equals operator we'd get hey these cats are equal as an answer because they you know they have the same properties they look the same now on the other hand the is operator Compares identities so if we compared our identical like seemingly identical cats or identical looking cats with the is operator then we'd get the answer that well they're two different cats right they're not the same cat like there's two of them like are you crazy so before I get all tangled up in this cat analogy um let's actually come up with some python code here so what we're going to do first is we're going to create a new list object now just um create this new list one two three and then we're going to create another variable that points to the same list so now these two variables A and B they're pointing to the same list so when we inspect a you can see here okay this is the contents we well we put in earlier and if we inspect uh B then we get the same result now at this point we we know that they kind of look the same right so if we compare them with the uh equals equals operator we get true as the answer because well you know they they look the same they have the same uh seemingly the same content now what that doesn't tell us however is whether or not A and B are actually the same object I mean in this case we know because we created them and we assigned B to point to uh the the same object that a points to but suppose we didn't know right like how could we find out and this is where the is operator comes in so if we went a a is B then in this case python would tell us yeah they're the same object like they are the same thing and uh that would mean you know if I go in and uh change a by let's say putting in a string if I change a that would also change B because they're pointing to the same underlying object right and so now um I'm actually going to undo this and just you know create create a new list here and then replay everything I did before so now we're you know I undid this change here where I added this string so what we're going to do now is we're going to create a new copy off the this list that we're going to call C and the way we can do that is just by calling uh the list function or the built-in list function on a again what that's going to do it's going to create a shallow copy that will look exactly the same so let's take at look at a again look at B again and then look at Z and you can see here they all look exactly the same right if you just looking at their contents they look exactly the same so now this is where it gets interesting right because when I go and compare a to c then we get the answer okay they're they look identical uh they are considered equal now if I go and do a is C then we get a a different result because python tells us hey they're not the same object they might look identical but they're not the same freaking cats they're two different cats that just look the same right they're both like they both have black fur and the same uh eye color and whatnot but they're they're two different cats and really this is the key distinction between equals equals and the is operator because the is operator or an is expression it evaluates to true if two variables point point to the same like identical object and the equals equals operator or an equals equals expression evaluates to true if both objects are equal or have the same contents but they're not necessarily the same object like we don't care about that all right so I hope this clarified this difference to you and uh just think of cats so every time you're going to have to make a decision between equals equals and is just think of twin cats I mean think of cats all day you can also think of dogs it works the same way with dogs but that's really the key distinction you need to remember all right so I hope this was helpful uh like I said if you enjoyed this kind of micro example where I'm explaining an aspect of python part of the language um in sufficient detail to kind of you know get started with it and really understand the underlying principle then uh be sure to check out my new book it's available for Early Access right now and I think you might really enjoy it cool talk to you soon thanks so much
Original Description
https://dbader.org/python-tricks ► Write clean & Pythonic code and start using advanced features in your Python code
It's easy to get tripped up by Python's "is" and "==" operators for object comparison. In this video I'll explain the difference with a few easy to understand examples.
There's a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.
The == operator compares by checking for equality - the "is" operator, however, compares identities.
The difference between them breaks down to down to two short definitions:
An is expression evaluates to True if two variables point to the same (identical) object.
An == expression evaluates to True if the objects referred to by the variables are equal (have the same contents).
Check out this tutorial if you want to drill deeper: https://dbader.org/blog/difference-between-is-and-equals-in-python
FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery
PYTHON TRICKS: THE BOOK https://dbader.org/pytricks-book
SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube
* * *
► Python Developer MUGS, T-SHIRTS & MORE: https://nerdlettering.com
FREE Python Tutorials & News:
» Python Tutorials: https://dbader.org
» Python News on Twitter: https://twitter.com/@dbader_org
» Weekly Tips for Pythonistas: https://dbader.org/newsletter
» Subscribe to this channel: https://dbader.org/youtube
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 35 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
▶
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: Python for Data
View skill →Related Reads
📰
📰
📰
📰
The Future of Mobile App Development: Trends, Technologies and Business Impact
Medium · AI
I Collected 1,000 AI GitHub Repositories So You Don’t Have To
Medium · AI
I Collected 1,000 AI GitHub Repositories So You Don’t Have To
Medium · Python
Building Video Recommendation Graphs With Apache AGE and Cypher
Dev.to · ahmet gedik
🎓
Tutor Explanation
DeepCamp AI