Skip to content

Variables and Data Types

A variable is a named reference to a value stored in memory. Python variables are labels/pointers attached to objects, not containers.

# Simple assignment
x = 10
name = "Alice"
pi = 3.14159
# Multiple assignment
a = b = c = 0
x, y = 10, 20
# Swap variables (Pythonic!)
x, y = y, x
# Extended unpacking
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]
TypeConventionExample
Variablessnake_caseuser_name
ConstantsUPPER_SNAKE_CASEMAX_SIZE
ClassesPascalCaseUserAccount
Functionssnake_casecalculate_tax()
x = 42 # int
y = 3.14 # float
s = "hello" # str
lst = [1, 2, 3] # list
t = (1, 2, 3) # tuple
d = {"key": "value"} # dict
st = {1, 2, 3} # set
flag = True # bool
nothing = None # NoneType
flowchart TB
subgraph Mutable["Mutable Objects (can change in place)"]
direction TB
L["list"]
D["dict"]
S["set"]
BA["bytearray"]
end
subgraph Immutable["Immutable Objects (cannot change in place)"]
direction TB
I["int"]
F["float"]
ST["str"]
T["tuple"]
BO["bool"]
FR["frozenset"]
end
style Mutable fill:#1e40af,color:#fff
style Immutable fill:#7c3aed,color:#fff
style L fill:#2563eb,color:#fff
style D fill:#2563eb,color:#fff
style S fill:#2563eb,color:#fff
style BA fill:#2563eb,color:#fff
style I fill:#8b5cf6,color:#fff
style F fill:#8b5cf6,color:#fff
style ST fill:#8b5cf6,color:#fff
style T fill:#8b5cf6,color:#fff
style BO fill:#8b5cf6,color:#fff
style FR fill:#8b5cf6,color:#fff
x = 5 # int
x = "hello" # now str
x = [1, 2, 3] # now list
# Preferred: isinstance()
print(isinstance(x, int)) # True
print(isinstance(x, (int, float))) # True — multiple types

Understanding Python’s reference model and dynamic typing is fundamental to writing correct code and avoiding bugs.

  • Confusing = (assignment) with == (comparison)
  • Not understanding that variables reference objects
  • Thinking variables are boxes (they’re labels!)

Q1: What is dynamic typing in Python?

A: Variable types are determined at runtime. A variable can reference any type of object, and you can change it at any time.

Q2: Why does a = [1,2,3]; b = a; b.append(4) modify a?

A: Because b and a reference the same list object. Variables are labels, not containers.

  1. Swap two variables without using a third variable.
  2. Check the type of different values using type() and isinstance().
  3. Demonstrate Python’s reference model with lists.