Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Python "is" statement and tuples

Why is () is () true, yet (0,) is (0,) is false?

I thought they would be the same object. However, I'm apparently missing something.

like image 675
rectangletangle Avatar asked Apr 04 '12 04:04

rectangletangle


People also ask

Is Python a tuple?

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.

Is a list a tuple Python?

There is a difference in python tuple vs list and the syntax for both tuple and the list also differs such as, the items in tuples are surrounded by parentheses( ) and the items in lists are surrounded by square brackets [ ]. The list consumes more storage space than the tuples.

Why does Python have both lists and tuples?

List and Tuple in Python are the classes of Python Data Structures. The list is dynamic, whereas the tuple has static characteristics. This means that lists can be modified whereas tuples cannot be modified, the tuple is faster than the list because of static in nature.

What is the main difference between a Python list and a tuple?

The primary difference between tuples and lists is that tuples are immutable as opposed to lists which are mutable. Therefore, it is possible to change a list but not a tuple. The contents of a tuple cannot change once they have been created in Python due to the immutability of tuples.


1 Answers

is tests to see if both sides of the statement share the same memory address. It's basically a shorthand for id(a) == id(b)

>>> print id(()), id(())
30085168 30085168
>>> print id((0,)), id((0,))
38560624 38676432
>>>

As () happens fairly frequently, it is actually treated as a singleton by the Python Interpreter (just like integers from 0 to 255, empty strings, empty lists, etc.). When comparing (0, ) to (0, ) to the interpreter they are actually different variables in memory. If they were mutable, you could modify the first, and the second wouldn't change, hence they are not the same (a is not b).

like image 148
Esteban Küber Avatar answered Sep 25 '22 00:09

Esteban Küber