1.9 KiB
Python List Exercises
These exercises will help you get really good at using lists in Python. You'll practice things like loops, slicing, grouping, and working with nested lists.
Exercise 1
Flatten a Nested List
Problem
Write a function flatten_list(nested_list)
that takes a list which may contain nested lists of any depth, and returns a single, flat list.
Example
flatten_list([1, [2, 3], [4, [5, 6], 7]])
# Output: [1, 2, 3, 4, 5, 6, 7]
Concepts
- Recursion
isinstance
type checkingextend
vsappend
Exercise 2
Group Consecutive Duplicates
Problem
Write a function group_consecutive(lst)
that groups consecutive identical elements into sublists.
Example
group_consecutive([1, 1, 2, 2, 2, 3, 1, 1])
# Output: [[1, 1], [2, 2, 2], [3], [1, 1]]
Concepts
- Iteration with state tracking
- Temporary sublists
for
loops with conditionals
Exercise 3
Rotate List k Times
Problem
Write a function rotate_list(lst, k)
that rotates the list right by k
steps.
BONUS: Support negative
k
to rotate left.
Example
rotate_list([1, 2, 3, 4, 5], 2)
# Output: [4, 5, 1, 2, 3]
Concepts
- Identify concepts yourself.
Exercise 4
List Difference by Value and Order
Problem
Write a function diff_lists(a, b)
that removes each occurrence in b
from a
, respecting the number of times elements occur.
Example
diff_lists([1, 2, 2, 3, 4], [2, 4])
# Output: [1, 2, 3]
One
2
and the4
are removed. The second2
remains.
Concepts
- Element-by-element removal
- List copying
in
with deletion logic
✅ Pro Tips
-
Try solving without using libraries.
-
Then try versions using
collections.Counter
,itertools
, orfunctools
for practice. -
Write unit tests for edge cases:
- Empty lists
- Deep nesting
- Large
k
values - Negative numbers