diff --git a/list.md b/list.md new file mode 100644 index 0000000..fd802a4 --- /dev/null +++ b/list.md @@ -0,0 +1,103 @@ + +# 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 + +```python +flatten_list([1, [2, 3], [4, [5, 6], 7]]) +# Output: [1, 2, 3, 4, 5, 6, 7] +``` + +### Concepts + +- Recursion +- `isinstance` type checking +- `extend` vs `append` + +--- + +## Exercise 2: Group Consecutive Duplicates + +### Problem + +Write a function `group_consecutive(lst)` that groups consecutive identical elements into sublists. + +### Example + +```python +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 + +```python +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 + +```python +diff_lists([1, 2, 2, 3, 4], [2, 4]) +# Output: [1, 2, 3] +``` + +> One `2` and the `4` are removed. The second `2` 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`, or `functools` for practice. + +- Write unit tests for edge cases: + - Empty lists + - Deep nesting + - Large `k` values + - Negative numbers +