Difficulty: Beginner
What are Python's built-in data types? Explain mutability and how variables work internally.
Python's built-in data types include: - Numeric: int, float, complex - Sequence: str, list, tuple, range - Set: set, frozenset - Mapping: dict - Boolean: bool - Binary: bytes, bytearray, memoryview - None: NoneType
Variables in Python are references (labels) pointing to objects in memory, not boxes holding values. Assignment binds a name to an object.
Mutable objects (list, dict, set) can be changed in place. Immutable objects (int, float, str, tuple, frozenset) cannot - operations create new objects.
a = [1, 2, 3]
b = a # b points to the SAME list object
b.append(4)
print(a) # [1, 2, 3, 4] - a is affected!
print(a is b) # True - same object in memory
print(id(a) == id(b)) # True
# Compare with immutable types
x = 10
y = x
y += 5
print(x) # 10 - x is NOT affected
print(x is y) # False - y now points to a new int object
For mutable objects, assignment copies the reference, not the value. Both variables point to the same object. For immutables, operations create new objects.
# Type checking
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type([1, 2])) # <class 'list'>
print(isinstance(42, int)) # True
print(isinstance(True, int)) # True - bool is a subclass of int!
# Type casting
print(int("42")) # 42
print(float("3.14")) # 3.14
print(str(42)) # '42'
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1, 2, 3])) # (1, 2, 3)
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
isinstance() is preferred over type() for checking because it handles inheritance. Falsy values: 0, 0.0, '', [], {}, set(), None, False.
# Immutable: str, int, float, tuple, frozenset
s = "hello"
# s[0] = 'H' # TypeError! Strings are immutable
s = s.capitalize() # Creates a NEW string
print(s) # 'Hello'
# Mutable: list, dict, set
lst = [1, 2, 3]
print(id(lst)) # e.g., 140234567890
lst.append(4)
print(id(lst)) # SAME id - modified in place
# Gotcha: tuple with mutable elements
t = ([1, 2], [3, 4])
# t[0] = [5, 6] # TypeError - can't reassign tuple element
t[0].append(3) # But CAN mutate the list inside!
print(t) # ([1, 2, 3], [3, 4])
Immutability means the object itself cannot change, but a tuple can contain mutable objects whose contents can still be modified.
Variables, Data Types, Type Casting, Mutability, id() and is