Skip to content
Fix Code Error

String comparison in Python: is vs. ==

March 13, 2021 by Code Error
Posted By: Anonymous

I noticed a Python script I was writing was acting squirrelly, and traced it to an infinite loop, where the loop condition was while line is not ''. Running through it in the debugger, it turned out that line was in fact ''. When I changed it to !='' rather than is not '', it worked fine.

Also, is it generally considered better to just use ‘==’ by default, even when comparing int or Boolean values? I’ve always liked to use ‘is’ because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap…), but I wonder if it’s intended to just be reserved for when you care about finding two objects with the same id.

Solution

For all built-in Python objects (like
strings, lists, dicts, functions,
etc.), if x is y, then x==y is also
True.

Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.

Also, is it generally considered better to just use ‘==’ by default, even
when comparing int or Boolean values?

You use == when comparing values and is when comparing identities.

When comparing ints (or immutable types in general), you pretty much always want the former. There’s an optimization that allows small integers to be compared with is, but don’t rely on it.

For boolean values, you shouldn’t be doing comparisons at all. Instead of:

if x == True:
    # do something

write:

if x:
    # do something

For comparing against None, is None is preferred over == None.

I’ve always liked to use ‘is’ because
I find it more aesthetically pleasing
and pythonic (which is how I fell into
this trap…), but I wonder if it’s
intended to just be reserved for when
you care about finding two objects
with the same id.

Yes, that’s exactly what it’s for.

Answered By: Anonymous

Related Articles

  • Sinon stubs not been called
  • How do I include certain conditions in SQL Count
  • What is the worst programming language you ever worked with?
  • Why are CSS keyframe animations broken in Vue…
  • Callback functions in C++
  • How to prevent scrolling the whole page?
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • next/link losing state when navigating to another page
  • How to filter a RecyclerView with a SearchView
  • Why does C++ code for testing the Collatz conjecture…
  • Adding gif image in an ImageView in android
  • Fastest way to iterate over all the chars in a String
  • How does PHP 'foreach' actually work?
  • What is an optional value in Swift?
  • Can't install via pip because of egg_info error
  • django ajax like button with css classes
  • What's the difference between eval, exec, and compile?
  • Reference — What does this symbol mean in PHP?
  • Use of Jquery on scroll event
  • Logging best practices
  • problem with client server unix domain stream…
  • Javax.net.ssl.SSLHandshakeException:…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Knight's tour Problem - storing the valid moves then…
  • How to format a phone number in a textfield
  • What's the best way to get the last element of an…
  • Algorithm to randomly generate an…
  • What is a NullReferenceException, and how do I fix it?
  • Converting Oracle SQL Procedure into MySQL Stored Procedure
  • rails change the background of my like button when…
  • How do the PHP equality (== double equals) and…
  • What are type hints in Python 3.5?
  • Accessing a Shared File (UNC) From a Remote,…
  • Draw in Canvas by finger, Android
  • Getting infinite loop after entering 2 objects to…
  • Undefined reference to 'vtable for ✘✘✘'
  • Auto-fit TextView for Android
  • Start redis-server with config file
  • Equals(=) vs. LIKE
  • How do I merge two dictionaries in a single…
  • How do I expand the output display to see more…
  • What are the undocumented features and limitations…
  • The definitive guide to form-based website authentication
  • Tkinter understanding mainloop
  • How can I determine whether a 2D Point is within a Polygon?
  • data.table vs dplyr: can one do something well the…
  • "The system cannot find the file specified"
  • What is your most productive shortcut with Vim?
  • How to set HTML5 required attribute in Javascript?
  • What is an IndexOutOfRangeException /…
  • Memcached vs. Redis?
  • NextJS Button keeps clicking itself by React's useState
  • Is there some way to test my grammar which refer to…
  • How to implement a basic iterative pushdown…
  • C++ OpenGL stb_image.h errors
  • Smart way to truncate long strings
  • What does "Fatal error: Unexpectedly found nil while…
  • Baffling variadic templates exercise
  • How to generate a random string of a fixed length in Go?
  • Creating a singleton in Python
  • How to compare Boolean?
  • Java Array, Finding Duplicates
  • #define macro for debug printing in C?
  • SQL query return data from multiple tables
  • What is Ember RunLoop and how does it work?
  • Ukkonen's suffix tree algorithm in plain English
  • Clang vs GCC - which produces faster binaries?
  • How can I find the product GUID of an installed MSI setup?
  • C threads corrupting each other
  • Flex: REJECT rejects one character at a time?
  • ValueError: invalid literal for int () with base 10
  • Typeerror: n is undefined in underscore.min.js
  • C++ error: expected class member or base class name…
  • Convert True/False value read from file to boolean
  • jQuery Mobile: document ready vs. page events
  • What is a plain English explanation of "Big O" notation?
  • Elegant ways to support equivalence ("equality") in…
  • WAVE file unexpected behaviour
  • How to sort the keySet() of a TreeMap with keys…
  • How to increase the Java stack size?
  • How do I get the sums of the rows of a 2D array…
  • Function is Producing an Compile Erorr
  • How to solve the problem in Javascript code to…
  • Java 8 Iterable.forEach() vs foreach loop
  • For-each over an array in JavaScript
  • Simplest way to create Unix-like continuous pipeline…
  • Palindromic numbers in Java
  • Head pointer not accessible when creating a method…
  • What does a "Cannot find symbol" or "Cannot resolve…
  • Is it possible to print a variable's type in standard C++?
  • How to interpret this stack frame in my control stack?
  • Maximum XOR With an Element From Array | Leetcode
  • How to convert number to words in java
  • Implementation of user defined array on stack and/or…
  • Database development mistakes made by application developers
  • Java - Regex, nested recursion match
  • is there a way to use the forwarding of std::less…
  • How to use html template with vue.js
  • How to declare global variables in Android?
  • Comparing boxed Long values 127 and 128

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Disable ONLY_FULL_GROUP_BY

Next Post:

How do I make Git use the editor of my choice for commits?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error