Difficulty: Beginner
What are Python's built-in data types? Explain mutability and how variables actually work internally.
In Python a variable is just a name bound to an object; the object carries the type, not the name. Built-in types fall into numbers (int, float, complex, bool), text (str), sequences (list, tuple, range), sets (set, frozenset), mappings (dict), binary types (bytes, bytearray) and None. Mutable objects (list, dict, set, bytearray) can change in place, while immutable ones (int, float, str, tuple, frozenset, bytes) cannot, and that difference explains most surprising Python behaviour.
x = 10 creates (or reuses) an int object with value 10 and binds the name x to it. y = x does not copy anything; both names now reference the same object. Every object has:
id(obj) (in CPython, its memory address), fixed for its lifetimetype(obj)Python is dynamically typed (a name can be rebound to an object of any type) and strongly typed ("5" + 5 raises TypeError instead of silently converting).
| Type | Mutable? | Hashable (dict key / set member)? |
|---|---|---|
int, float, bool, str, bytes | No | Yes |
tuple, frozenset | No | Yes, if all items are hashable |
list, dict, set, bytearray | Yes | No |
When you "change" an immutable value, Python creates a new object and rebinds the name. s = "pay"; s += "tm" produces a new string; id(s) changes. With a list, nums.append(4) modifies the same object, so every name pointing to it sees the change.
This is why Python's argument passing is described as pass by object reference (or call by sharing): the function gets a reference to the same object. Mutating a list inside a function is visible to the caller; rebinding the parameter name is not.
== compares values by calling __eq__.is compares identity: are both names bound to the same object?Use is only for singletons: if x is None. CPython caches small integers from -5 to 256 and interns many short strings, so a = 256; b = 256; a is b is True but the same with 1000 may be False. That is an implementation detail; code that relies on it is a bug.
def add(item, cart=[]) creates the list once at definition time, so it is shared across calls. Use cart=None and create the list inside.grid = [[0] * 3] * 3 makes three references to one inner list. Use [[0] * 3 for _ in range(3)].list(a), a[:] and copy.copy(a) copy the outer list only; nested objects are shared. Use copy.deepcopy for full independence.t = ([1], 2); t[0].append(3) works because the tuple only fixes which objects it holds.0.1 + 0.2 == 0.3 is False. For money, store paise as int or use decimal.Decimal.Explicit casts use the type constructors: int("42"), float("3.5"), str(99), list("abc"). Prefer isinstance(x, int) over type(x) == int because it respects inheritance (note that bool is a subclass of int, so isinstance(True, int) is True). Type hints like count: int = 0 document intent and help tools such as mypy or Pyright, but the interpreter does not enforce them at runtime.
a = [1, 2]
b = a
b.append(3)
print(a, a is b) # same object
s = "pay"
before = id(s)
s += "tm" # new string object
print(s, id(s) == before)
x, y = 256, 256
print(x is y) # True in CPython (small int cache), never rely on it
print(0.1 + 0.2 == 0.3)
Mutating a list affects every name bound to it, while += on a string builds a new object. Small int caching is a CPython detail, not a language rule.
def add_bad(item, cart=[]): # list created once, at def time
cart.append(item)
return cart
print(add_bad("pen"))
print(add_bad("book")) # surprise: still has "pen"
def add_good(item, cart=None):
if cart is None:
cart = [] # fresh list each call
cart.append(item)
return cart
print(add_good("pen"))
print(add_good("book"))
Default values are evaluated once when the function is defined, so a mutable default is shared by every call.
Names and References, Built-in Data Types, Mutability, id() and is, Dynamic Typing, Integer Caching