"is" vs "==" in Python – What's the Difference? (And When to Use Each)

Real Python · Beginner ·🛠️ AI Tools & Apps ·9y ago

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 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

Related Reads

📰
The Future of Mobile App Development: Trends, Technologies and Business Impact
Learn how AI, 5G, and smarter tools are revolutionizing mobile app development and its business impact
Medium · AI
📰
I Collected 1,000 AI GitHub Repositories So You Don’t Have To
Explore 1,000 AI GitHub repositories to discover new projects and learn from existing ones, and understand the importance of open-source AI development
Medium · AI
📰
I Collected 1,000 AI GitHub Repositories So You Don’t Have To
Explore 1,000 AI GitHub repositories to discover new projects and learn from existing ones, and learn how to collect and analyze GitHub data using the GitHub API
Medium · Python
📰
Building Video Recommendation Graphs With Apache AGE and Cypher
Learn to build video recommendation graphs using Apache AGE and Cypher, replacing complex SQL self-joins
Dev.to · ahmet gedik
Up next
How I Used AI to Design a Kitchen Around One Item
Alicia Lyttle
Watch →