invictus invictus - 5 months ago 17
Python Question

To `is` and to `is not` in Python

Consider the following. The first element in a list

is an integer, confirmed by

Yet when
is not int
is invoked, it says it is not an integer.

a = [1, 2.0, 3, 4, 5.0, 9.9, "abc"]
a[0] is int # this says "False"

Can somebody explain?

P.S. Apologies to Hemingway for the title

Edit I don't see how this question is the same as the one rolled out by @davidism et al. That question asks about "objects". This one asks about "is" and "is not".


The reason a[0] is not int is true is that a[0] is an integer, and int is the integer type, a sort of template for creating integers. They are not the same object any more than 1 and 2 are the same object, or pi and "pumpkin" are the same object. And that's what is tests for: whether two values are literally the same object.

In object-oriented programming we say that the integer a[0] is an instance of the int type (or class, they are essentially synonyms). To express this in Python, use isinstance(a[0], int). You could also use type(a[0]) is int. The advantage of isinstance() is that it also detects when a[0] is an instance a type based on int (called a subclass or subtype).