# Variables & Data Types

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

Canonical: https://www.internhack.in/learn/interview/python-interview/python-variables-types
Last updated: 2026-11-28

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:

- an **identity**, shown by `id(obj)` (in CPython, its memory address), fixed for its lifetime
- a **type**, shown by `type(obj)`
- a **value**

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

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

### == vs is, and small-object caching

- `==` 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.

### Gotchas that come up in interviews

- **Mutable default arguments**: `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.
- **List multiplication**: `grid = [[0] * 3] * 3` makes three references to one inner list. Use `[[0] * 3 for _ in range(3)]`.
- **Shallow vs deep copy**: `list(a)`, `a[:]` and `copy.copy(a)` copy the outer list only; nested objects are shared. Use `copy.deepcopy` for full independence.
- **Tuples are not deeply immutable**: `t = ([1], 2); t[0].append(3)` works because the tuple only fixes which objects it holds.
- **Float precision**: `0.1 + 0.2 == 0.3` is `False`. For money, store paise as `int` or use `decimal.Decimal`.

### 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

- Variables are names bound to objects; assignment never copies
- Mutable: list, dict, set, bytearray. Immutable: int, float, str, tuple, frozenset, bytes
- Only hashable (typically immutable) objects can be dict keys or set members
- Use == for value equality and is only for None and other singletons
- Never use a mutable object as a default argument value

## Common follow-up questions

- Is Python pass by value or pass by reference?
- What is the difference between a shallow copy and a deep copy?
- Why can a tuple containing a list not be used as a dict key?
- Why does 0.1 + 0.2 not equal 0.3, and how would you store money values?
- What does it mean that Python is dynamically but strongly typed?

## Interview tips

- Say 'names are bound to objects' early; it frames every follow-up correctly
- Bring up the mutable default argument bug unprompted; it is a classic
- Avoid saying Python is pass by reference; say pass by object reference and explain with a list example

## Concepts covered

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

Previous: [GIL & Concurrency](https://www.internhack.in/learn/interview/python-interview/python-gil) · Next: [Strings & String Methods](https://www.internhack.in/learn/interview/python-interview/python-strings) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [Lists, Tuples & Sets](https://www.internhack.in/learn/interview/python-interview/python-lists-tuples-sets)
- [Dictionaries & Operations](https://www.internhack.in/learn/interview/python-interview/python-dictionaries)
- [Control Flow & Loops](https://www.internhack.in/learn/interview/python-interview/python-control-flow)
- [Functions & Arguments](https://www.internhack.in/learn/interview/python-interview/python-functions)
- [\*args & kwargs](https://www.internhack.in/learn/interview/python-interview/python-args-kwargs)
- [List Comprehensions](https://www.internhack.in/learn/interview/python-interview/python-list-comprehensions)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
