Topic 2 of 64
Types
Overview
Python has rich built-in data types. Understanding when to use list, tuple, set, and dict is fundamental — they have very different performance characteristics and use cases in real applications.
Syntax
python
# Numeric
x = 42 # int
y = 3.14 # float
z = 3 + 4j # complex
# String
s = "Hello"
s = 'World'
s = """Multi
line"""
# Boolean
flag = True # or False
# Collections
my_list = [1, 2, 3] # ordered, mutable
my_tuple = (1, 2, 3) # ordered, immutable
my_set = {1, 2, 3} # unordered, unique
my_dict = {"key": "value"} # key-value pairs
# Type checking
type(42) # <class 'int'>
isinstance(42, int) # TrueCommon Pitfalls
- Lists are O(n) for 'in' checks; sets are O(1) — for large lookups, always use sets.
- Tuples with a single element need a trailing comma: (42,) — not (42) which is just parentheses.
- Interview tip: dict maintains insertion order in Python 3.7+. set is unordered — never rely on set order.
Real-World Example
Using appropriate data types for a user session manager:
example
python
# Use set for O(1) lookup — checking active sessions
active_sessions: set[str] = set()
active_sessions.add("session_abc123")
active_sessions.add("session_xyz789")
is_active = "session_abc123" in active_sessions # True, O(1)
# Use tuple for immutable coordinates/config
DB_CONFIG = ("localhost", 5432, "mydb") # can't be accidentally modified
# Use dict for structured data
user = {
"id": 42,
"name": "Ananya Singh",
"roles": ["admin", "editor"], # list for ordered, mutable
"metadata": {"last_login": "2025-06-13"}
}