Variables & Data Types

Difficulty: Beginner

Question

What are Python's built-in data types? Explain mutability and how variables actually work internally.

Answer

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.

Names point to objects

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:

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).

Mutable vs immutable in practice

TypeMutable?Hashable (dict key / set member)?
int, float, bool, str, bytesNoYes
tuple, frozensetNoYes, if all items are hashable
list, dict, set, bytearrayYesNo

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.

== vs is, and small-object caching

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.

Gotchas that come up in interviews

Type conversion and checking

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.

What happens with a = [1, 2]; b = a; b.append(3). Assignment binds names to objects; it never copies them.
  1. a = [1, 2]: A list object is created and the name a points to it.
  2. b = a: b is bound to the very same list; no copy is made.
  3. b.append(3): The shared list is mutated in place.
  4. print(a) shows [1, 2, 3]: Both names see the change because a is b is True.
  5. b = b + [4]: Creates a new list and rebinds b; a is untouched.

Code examples

Identity, mutation and rebinding

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.

Mutable default argument trap and fix

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.

Key points

Common follow-up questions

Interview tips

Concepts covered

Names and References, Built-in Data Types, Mutability, id() and is, Dynamic Typing, Integer Caching

More Python Interview questions