Topic 44 of 64
List Construction & Indexing
Overview
Lists are Python's most used mutable sequence type. Understanding construction, positive/negative indexing, and nested lists is the baseline for all data manipulation tasks.
Syntax
python
# Construction
empty = []
nums = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# Positive indexing (0-based)
nums[0] # 1 (first)
nums[2] # 3 (third)
# Negative indexing
nums[-1] # 5 (last)
nums[-2] # 4 (second to last)
# Nested lists
matrix = [[1, 2], [3, 4], [5, 6]]
matrix[1][0] # 3Common Pitfalls
- Accessing an out-of-range index raises IndexError — always check len(list) or use try/except.
- Lists can hold mixed types but this is usually a design smell — prefer homogeneous types for clarity.
- Interview tip: To create a list of repeated values use [0] * 5 (gives [0, 0, 0, 0, 0]) — but NEVER use [[]] * n for nested lists as all sublists share the same reference.
Real-World Example
Working with a queue-style list for a task management system
example
python
tasks = ["design", "develop", "test", "deploy"]
current = tasks[0] # "design" (first task)
last = tasks[-1] # "deploy" (last task)
middle = tasks[1:3] # ["develop", "test"]
print(f"Current: {current}, Upcoming: {middle}, Final: {last}")