1

I'm testing Python's Boolean expressions. When I run the following code:

x = 3
print type(x)
print (x is int)
print (x is not int)

I get the following results:

<type 'int'>
False
True

Why is (x is int) returning false and (x is not int) returning true when clearly x is an integer type?

6
  • 4
    int is a class. if you type just int you get <class 'int'> Commented Sep 29, 2016 at 12:59
  • 9
    is compares references. You want isinstance(x,int) Commented Sep 29, 2016 at 12:59
  • Python is not English. The is operator does something very specific, which appears to differ from what you expect. Commented Sep 29, 2016 at 13:01
  • 2
    is is not a Boolean operator, it's an identity operator Commented Sep 29, 2016 at 13:02
  • 2
    Take a look at this question for more details: stackoverflow.com/questions/13650293/… Commented Sep 29, 2016 at 13:02

3 Answers 3

2

The best way to do this is use isinstance()

so in your case:

x = 3
print isinstance(x, int)

Regarding python is

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

Taken from docs

Sign up to request clarification or add additional context in comments.

Comments

1

Try typing these into your interpreter:

type(x)
int
x is 3
x is not 3
type(x) is int
type(x) is not int

The reason that x is int is false is that it is asking if the number 3 and the Python int class represent the same object. It should be fairly clear that this is false.

As a side note, Python's is keywords can work in some unexpected ways if you don't know exactly what it is doing, and you should almost certainly be avoiding it if you are ever testing equality. That being said, experimenting with it outside of your actual program is a very good idea.

Comments

0

If you want to use is you should do:

>>> print (type(x) is int)
True

1 Comment

Thank you everyone for helping me understand Python's 'is' operator. I had read that 'is' could be used to check whether an identifier is of a specific type. Thank you coder for showing me the correct syntax for doing so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.