Flat_Eric working on his laptop

Is

Is, is = to == ... what?

is vs ==

Before we explain the difference between is and ==, have a look at the expressions below and take a guess at what each one will return before you run them.

  • print(True == 1)
  • print(' ' == 1)
  • print([] == 1)
  • print(10 == 10.0)
  • print([] == [])

Loading quiz...

== Equality of Value

The == operator checks if two values are equal. However it is important to understand that equal does not always mean the same type. For example '1' == 1 returns False because even though they look similar, '1' is a string and 1 is an integer. They are not the same type so Python considers them unequal.

is - Equality of Memory

The is keyword does something completely different. Instead of asking "are these values equal?", it asks "are these the exact same object in memory?" Every time Python creates a value it stores it somewhere in memory. is checks whether two variables are pointing to the exact same location in memory, not just whether they contain the same value.

This is why '1' is '1' returns True and True is True returns True. Python stores simple values like short strings and Booleans in a shared memory location and reuses them, so they point to the same place.

But [] is [] returns False. This surprises a lot of beginners. Even though both lists are empty and look identical, every time you create a list Python creates a brand new object in a brand new location in memory. The two lists may contain the same values but they live in different places, so is returns False.

The same applies to any list regardless of its contents. Even [1, 2, 3] is [1, 2, 3] returns False because the two lists were created separately and occupy different locations in memory.

To summarise:

Try each of the following in the box below and run it each time to see what Python returns:

  • print('1' == 1)
  • print('1' is '1')
  • print(True is True)
  • print([] is [])
  • print([1, 2, 3] is [1, 2, 3])
  • print([1, 2, 3] == [1, 2, 3])

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Predict the Output

  • print(1 == 1.0)
  • print(1 is 1.0)
  • print(True == 1)
  • print(True is 1)
  • print(None is None)

Exercise 2: The List Trap

  • print(list_a == list_b)
  • print(list_a is list_b)

Exercise 3: Same Object

  • print(list_a == list_b)
  • print(list_a is list_b)

Exercise 4: Spot the Difference

  • a = 'hello'
  • b = 'hello'
  • print(a == b)
  • print(a is b)
  • c = ''.join(['h','e','l','l','o'])
  • print(a == c)
  • print(a is c)

Exercise 5: When to use is and When to use ==

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course