Python Basics — Lists: Practice Exercises
Lists — Practice Exercises
Test your understanding of list creation, methods, slicing, comprehensions, and nested lists.
Exercise 1 — Reverse Without Built-in
Write a function reverse_list(lst) that returns a new list with elements in reverse order. Do not use .reverse(), reversed(), or [::-1].
Show Solution
def reverse_list(lst):
result = []
for i in range(len(lst) - 1, -1, -1):
result.append(lst[i])
return result
print(reverse_list([1, 2, 3, 4, 5])) # [5, 4, 3, 2, 1]
print(reverse_list(["a", "b", "c"])) # ['c', 'b', 'a']
print(reverse_list([])) # []
Exercise 2 — Remove Duplicates (Preserve Order)
Write a function remove_duplicates(lst) that returns a new list with duplicates removed, preserving the original order.
Show Solution
def remove_duplicates(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(remove_duplicates([1, 2, 2, 3, 1, 4, 3]))
# [1, 2, 3, 4]
print(remove_duplicates(["a", "b", "a", "c", "b"]))
# ['a', 'b', 'c']
Exercise 3 — Flatten a Nested List
Write a function flatten(nested) that takes a list of lists and returns a single flat list.
Show Solution
def flatten(nested):
return [item for sublist in nested for item in sublist]
print(flatten([[1, 2], [3, 4], [5]]))
# [1, 2, 3, 4, 5]
print(flatten([["a", "b"], ["c"]]))
# ['a', 'b', 'c']
print(flatten([[], [1], [], [2, 3]]))
# [1, 2, 3]
Exercise 4 — List Comprehension Practice
Using a list comprehension, create a list of all numbers from 1 to 50 that are divisible by 3 but not by 5. Then create a list of their squares.
Show Solution
# Numbers divisible by 3 but not by 5
numbers = [x for x in range(1, 51) if x % 3 == 0 and x % 5 != 0]
print(numbers)
# [3, 6, 9, 12, 18, 21, 24, 27, 33, 36, 39, 42, 48]
# Their squares
squares = [x ** 2 for x in numbers]
print(squares)
# [9, 36, 81, 144, 324, 441, 576, 729, 1089, 1296, 1521, 1764, 2304]
# Or in one step
squares = [x ** 2 for x in range(1, 51) if x % 3 == 0 and x % 5 != 0]
print(squares)
Exercise 5 — Matrix Rotation
Write a function rotate_90(matrix) that rotates a square matrix 90 degrees clockwise.
Hint: Transpose + reverse each row.
Input: Output:
1 2 3 7 4 1
4 5 6 → 8 5 2
7 8 9 9 6 3
Show Solution
def rotate_90(matrix):
n = len(matrix)
# Transpose then reverse each row
rotated = [[matrix[n - 1 - j][i] for j in range(n)] for i in range(n)]
return rotated
# Alternative using zip
def rotate_90_zip(matrix):
return [list(row) for row in zip(*matrix[::-1])]
m = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
result = rotate_90(m)
for row in result:
print(row)
# [7, 4, 1]
# [8, 5, 2]
# [9, 6, 3]
result2 = rotate_90_zip(m)
for row in result2:
print(row)
# [7, 4, 1]
# [8, 5, 2]
# [9, 6, 3]
Scoring Guide
| Score | Level |
|---|---|
| 5/5 | Excellent — lists mastered |
| 3-4/5 | Good — review slicing and comprehensions |
| 1-2/5 | Keep practicing — re-read the chapter |
Next chapter: Tuples →