List Exercises
Beginner Exercises
These exercises focus on fundamental list operations such as reversing, finding common elements, removing duplicates, flattening nested lists, and implementing sliding windows.
- Reverse a list without using reverse() or [::-1]
- Find common elements in two lists
- Remove duplicates from a list
- Flatten a nested list
- Implement a sliding window over a list
Example
# Example solution for removing duplicates
def remove_duplicates(lst):
seen = set()
return [x for x in lst if not (x in seen or seen.add(x))]
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))
Output
[1, 2, 3, 4, 5]
Intermediate Challenges
These problems involve more complex patterns such as encoding, rotation, matrix operations, and chunking.
Problem | Input Example | Expected Output |
---|---|---|
List rotation | [1,2,3,4,5], 2 | [4,5,1,2,3] |
Run-length encoding | ['a','a','b','c','c','c'] | [('a', 2), ('b', 1), ('c', 3)] |
Matrix transposition | [[1,2],[3,4],[5,6]] | [[1,3,5],[2,4,6]] |
Moving average | [1,2,3,4,5], 3 | [2.0, 3.0, 4.0] |
List chunking | [1,2,3,4,5,6], 2 | [[1,2], [3,4], [5,6]] |
Advanced Problems
For advanced practice, you can implement classic algorithms using lists. Quicksort is a well-known recursive sorting algorithm that demonstrates the power of list comprehensions and recursion.
Example
# Implement quicksort
def quicksort(lst):
if len(lst) <= 1:
return lst
pivot = lst[len(lst) // 2]
left = [x for x in lst if x < pivot]
middle = [x for x in lst if x == pivot]
right = [x for x in lst if x > pivot]
return quicksort(left) + middle + quicksort(right)
print(quicksort([3,6,8,10,1,2,1]))
Output
[1, 1, 2, 3, 6, 8, 10]