Python Tutorial
Python Access List Items
List items are indexed. The first item has index 0. Negative indexes count from the end.
Access Items
Print the second item (index 1).
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
print(thislist[-1])Range of Indexes
Specify a start and end. The return value is a new list. The end is excluded.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
print(thislist[:4])
print(thislist[2:])
print(thislist[-4:-1])Check if Item Exists
Use the in keyword.
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, apple is in the list")📘 Real-World Deep Dive
Knowing how to read individual elements and ranges from a list — <code>xs[i]</code>, <code>xs[i:j]</code>, <code>xs[i:j:k]</code>, and the safe variants — is the foundation of every list-manipulating algorithm.
Real-Life Scenario
Walk a 2-D matrix representation given as a flat list, returning rows and columns as views without copying data.
Real-Life Example
def rows(flat: list[int], cols: int) -> list[list[int]]:
return [flat[i:i + cols] for i in range(0, len(flat), cols)]
matrix_flat = list(range(1, 13))
M = rows(matrix_flat, cols=4)
print("row 0:", M[0])
print("row 2:", M[2])
print("first col :", [r[0] for r in M])
print("last col:", [r[-1] for r in M])
print("diagonal :", [M[i][i] for i in range(4)])
print("reversed :", M[::-1])Expected Output
row 0: [1, 2, 3, 4]
row 2: [9, 10, 11, 12]
first col : [1, 5, 9]
last col: [4, 8, 12]
diagonal : [1, 6, 11, 16]
reversed : [[9, 10, 11, 12], [5, 6, 7, 8], [1, 2, 3, 4]]Common mistakes
- A negative index wraps to the end:
xs[-1]is the last item. xs[start:stop]excludesstop;xs[:stop]is identical for sane values.- Accessing an out-of-range index raises
IndexError— guard with length checks or use slicing.
🚀 Performance & Best Practices
- Indexing is O(1); looping with
enumerate(xs)avoids the index lookup entirely. - Slicing always creates a copy — for a 1 GB list, that's costly on memory.
- For matrix views, store rows as separate lists to avoid O(n) column scans.
🧪 Try It Yourself
- Implement
safe_get(xs, i, default=None)for read-with-default semantics. - Write a
padded(M, n)helper that returns rows of length n with zeros for missing cells. - Profile
xs[::2]vs. a generator that callsxs[i]every other iteration.