Gal Sheldon
Gal Sheldon

Reputation: 75

is the 'is' keyword in python a function?

I am attempting to understand under what definition the 'is' keyword in Python falls under.

In the course I am taking, the instructor puts great emphasis on the difference between functions and method (class functions). When asked, the instructor said its a function and referenced me to Python's Operator class and it's 'is_' method (which is simply a method to allow easy use of an operator, and not even the referred keyword).

a is b
operator.is_(a,b)

I find myself struggling with the answer I have been given. I would greatly appreciate it if you could, based on my instructors emphasis on functions and methods, explain if 'is' falls in any of them. If not, what is the right way to view it?

Upvotes: 1

Views: 744

Answers (2)

Cloudy_Green
Cloudy_Green

Reputation: 113

The is operator checks whether both the operands refer to the same object or not. It compares identities. Whereas == compares the values of both the operands and checks for value equality. It compares by checking for equality.

Following is an easy example:

# [] is an empty list

list1 = [] 
list2 = [] 
list3 = list1 

if (list1 == list2): 
    print("True") 
else: 
    print("False")

if (list1 is list2): 
    print("True") 
else: 
    print("False") 

if (list1 is list3): 
    print("True") 
else:     
    print("False")

The output should be like the following:

True
False
True
  • In the example you provided:
  • in a is b, is is an operator
  • in operator.is()
  • operator is a module
  • is() is the function defined in the operator module.

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43136

  • is (as in a is b) is an operator. Specifically, a binary operator - because it takes two objects (a and b in the example) as input.

    What makes operators different from functions is the syntax - the two operands go on either side of the operator. If is were a function, it would be invoked like is(a, b).

  • operator.is_ is a function that takes two arguments (let's call them a and b) as input and returns a is b. It is the functional equivalent of the is operator. (The documentation of the operator module is even titled "Standard operators as functions".)

    Further, operator.is_ is not a method. operator is a module, not a class, and is_ is a function defined in that module.

Upvotes: 4

Related Questions