Access List Items
Indexing Techniques
Lists allow accessing elements by index. Indexing starts at 0 for the first element. Negative indices count from the end, with -1 being the last element. Lists also support slicing with [start:stop:step], which returns a new list. Using a negative step reverses the order.
data = ['a', 'b', 'c', 'd', 'e', 'f']
# Positive and negative indices
print(data[1]) # 'b'
print(data[-2]) # 'e'
# Slicing examples
print(data[1:4]) # ['b', 'c', 'd']
print(data[::2]) # ['a', 'c', 'e']
print(data[::-1]) # Reversed list
b e ['b', 'c', 'd'] ['a', 'c', 'e'] ['f', 'e', 'd', 'c', 'b', 'a']
Advanced Access Patterns
Python provides several ways to work with list items beyond simple indexing. Starred unpacking allows capturing multiple elements at once. The enumerate() function lets you loop with both index and value. Nested lists (lists inside lists) can be accessed by chaining indices.
# Unpacking with starred expressions
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
# Using enumerate for index-value pairs
for idx, val in enumerate(['x', 'y', 'z']):
print(f"Index {idx}: {val}")
# Nested list (matrix-style) access
matrix = [[1, 2], [3, 4]]
print(matrix[1][0]) # 3
1 [2, 3, 4] Index 0: x Index 1: y Index 2: z 3
Safe Access Techniques
Accessing a list with an invalid index raises IndexError. To avoid errors, you can use try-except blocks, create helper functions, or use slicing (which never raises errors, even if indices are out of range).
# Using try-except
try:
value = data[10]
except IndexError:
value = None
# Wrapper function for safe access
def safe_get(lst, index, default=None):
try:
return lst[index]
except IndexError:
return default
# Using slices (safe, returns empty list if out-of-range)
print(data[10:11]) # []