JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python Lists: 15 practice problems

UNIT 2 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise Lists nowAll topics

Theory: Lists in Python

THEORY
------
* A list is an ORDERED, MUTABLE collection that allows duplicates and mixed types.
      nums = [3, 1, 4]      empty = []      list("abc") -> ['a','b','c']     list(range(3))
* Indexing & slicing work exactly like strings (nums[-1], nums[1:3], nums[::-1]).
  BUT lists are mutable:  nums[0] = 10,  nums[1:3] = [7, 8],  del nums[0]

* METHODS
      add      append(x)  extend(iterable)  insert(i, x)
      remove   pop() -> last, pop(i) -> at i, remove(value) first match, clear()
      find     index(value)  count(value)  `x in nums`  (O(n) scan)
      order    sort(), sort(reverse=True), sort(key=len) — IN PLACE, returns None!
               sorted(nums) — returns a NEW list;   reverse() / reversed(nums)
      copy     copy(), nums[:], list(nums) — SHALLOW copies
* Built-ins: len, sum, min, max, sorted, any, all, enumerate, zip

* ALIASING (viva favourite):   b = a  makes b ANOTHER NAME for the same list.
      a = [1, 2]; b = a; b.append(3)  ->  a is now [1, 2, 3]
  Use b = a.copy() for an independent list. Nested lists need copy.deepcopy.
  Also: grid = [[0] * 3] * 3  creates 3 references to ONE row! Use [[0] * 3 for _ in range(3)].

* LIST COMPREHENSION:  [expr for x in iterable if condition]
      squares = [x * x for x in range(10) if x % 2 == 0]
      matrix  = [[r * c for c in range(3)] for r in range(3)]

* LISTS AS STACK / QUEUE:  stack: append + pop()  (LIFO)
                            queue: append + pop(0) is slow O(n) -> use collections.deque.popleft()

* COMMON ALGORITHM PATTERNS
      two pointers   i from start, j from end (or two lists) moving towards each other
      sliding window keep a running sum of the last k items: add new, subtract the one leaving
      prefix sums    running totals let you get any range sum quickly
* Complexity: index O(1), append O(1), insert/pop(0)/remove/in O(n), sort O(n log n).

15 Lists practice problems

1. Two Sum (LeetCode 1)

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [0, 1]. Use `return`, not print().
Real world: Find two items whose prices add up exactly to a gift card value.
Return [i, j] (i < j) of the two numbers adding to target. Exactly one answer exists.
    two_sum([2, 7, 11, 15], 9) -> [0, 1]
Ways: nested loops O(n²)  ·  dict of value->index O(n)
Solve “Two Sum (LeetCode 1)” in your browser →

2. Remove Duplicates, Keep Order

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [3, 1, 2]. Use `return`, not print().
Real world: A playlist where each song should appear once, in first-added order.
    dedupe_keep_order([3, 1, 3, 2, 1]) -> [3, 1, 2]
Viva: why does list(set(items)) not work here?
Solve “Remove Duplicates, Keep Order” in your browser →

3. Rotate List (LeetCode 189) — slicing

Easy3 ways to solve
📤 OUTPUT: return a list, e.g. [4, 5, 1, 2, 3]. Use `return`, not print().
    rotate_right([1, 2, 3, 4, 5], 2) -> [4, 5, 1, 2, 3]     (k may exceed len: use k % n)
Return a NEW list. Empty list -> [].
Solve “Rotate List (LeetCode 189) — slicing” in your browser →

4. Runner-Up Score — distinct values

Easy2 ways to solve
📤 OUTPUT: return an int (or None in the special case), e.g. 5. Use `return`, not print().
Return the second largest DISTINCT value, or None if it doesn't exist.
    second_largest([5, 9, 9, 3]) -> 5      second_largest([4, 4]) -> None
Ways: sorted(set(...))  ·  single pass tracking first and second (O(n))
Solve “Runner-Up Score — distinct values” in your browser →

5. Move Zeroes (LeetCode 283)

Easy3 ways to solve
📤 OUTPUT: return a list, e.g. [1, 3, 12, 0, 0]. Use `return`, not print().
Return a new list with all 0s at the end, other elements in original order.
    move_zeros([0, 1, 0, 3, 12]) -> [1, 3, 12, 0, 0]
Solve “Move Zeroes (LeetCode 283)” in your browser →

6. Merge Two Sorted Lists — two pointers (don't use sort/sorted!)

Medium2 ways to solve
📤 OUTPUT: return a list, e.g. [1, 2, 3, 4, 9, 10]. Use `return`, not print().
Real world: Merging two sorted leaderboards from different servers.
    merge_sorted([1, 4, 9], [2, 3, 10]) -> [1, 2, 3, 4, 9, 10]
Solve “Merge Two Sorted Lists — two pointers (don't use sort/sorted!)” in your browser →

7. Maximum Subarray (LeetCode 53) — Kadane's algorithm

Medium2 ways to solve
📤 OUTPUT: return an int, e.g. 6. Use `return`, not print().
Real world: Best consecutive run of days for a trading strategy (max total profit).
    max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) -> 6    ([4, -1, 2, 1])
nums has at least one element.
Hint: current = max(x, current + x); best = max(best, current)
Solve “Maximum Subarray (LeetCode 53) — Kadane's algorithm” in your browser →

8. Pagination — chunking with slicing

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [[1, 2], [3, 4], [5]]. Use `return`, not print().
Real world: Show search results 10 per page.
    paginate([1, 2, 3, 4, 5], 2) -> [[1, 2], [3, 4], [5]]
Solve “Pagination — chunking with slicing” in your browser →

9. Flatten One Level — nested loops / comprehension

Easy3 ways to solve
📤 OUTPUT: return a list, e.g. [1, 2, 3, 4, 5]. Use `return`, not print().
    flatten([[1, 2], [3], [], [4, 5]]) -> [1, 2, 3, 4, 5]
Solve “Flatten One Level — nested loops / comprehension” in your browser →

10. Transpose a Matrix — nested lists

Easy3 ways to solve
📤 OUTPUT: return a list, e.g. [[1, 4], [2, 5], [3, 6]]. Use `return`, not print().
    transpose([[1, 2, 3], [4, 5, 6]]) -> [[1, 4], [2, 5], [3, 6]]
Ways: nested loops  ·  comprehension  ·  [list(row) for row in zip(*matrix)]
Solve “Transpose a Matrix — nested lists” in your browser →

11. Running Sum (LeetCode 1480) — prefix sums

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [100, 80, 130]. Use `return`, not print().
Real world: Your bank statement's balance column.
    running_total([100, -20, 50]) -> [100, 80, 130]
Solve “Running Sum (LeetCode 1480) — prefix sums” in your browser →

12. Valid Parentheses (LeetCode 20) — list as a STACK

Medium2 ways to solve
📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Real world: Code editors highlight unmatched brackets.
s contains only ()[]{} characters. Every opener must be closed by the same type in the right order.
    valid_brackets("({[]})") -> True      valid_brackets("(]") -> False    valid_brackets("((") -> False
Solve “Valid Parentheses (LeetCode 20) — list as a STACK” in your browser →

13. Stock Moving Average — sliding window

Medium2 ways to solve
📤 OUTPUT: return a list, e.g. [20.0, 30.0, 40.0]. Use `return`, not print().
Real world: Trading apps draw a k-day moving average line.
Return the averages of every window of k consecutive prices, rounded to 2.
    moving_average([10, 20, 30, 40, 50], 3) -> [20.0, 30.0, 40.0]
If k > len(prices) return [].
Solve “Stock Moving Average — sliding window” in your browser →

14. Trading Desk Report — interview at a stock-broking app

Project1 way to solve
📤 OUTPUT: return a dict, e.g. {'max_profit': 5, 'buy_day': 1, 'sell_day': 4,…. Use `return`, not print().
Interviewer: "Given daily closing prices, report the best trade and the worst fall."
Return {"max_profit": best buy-then-sell profit (0 if prices only fall),
        "buy_day", "sell_day": indexes of that trade (None, None if no profit),
        "max_drawdown_pct": biggest % fall from a running peak to a LATER price, rounded to 2}
Single pass: keep the lowest price so far (update only on a strictly lower price) and the best profit
(update only when strictly greater), so ties keep the earliest days.
    trade_report([7, 1, 5, 3, 6, 4]) -> {"max_profit": 5, "buy_day": 1, "sell_day": 4, "max_drawdown_pct": 85.71}
Solve “Trading Desk Report — interview at a stock-broking app” in your browser →

15. Stage 8 — the Stack Machine (a list used as a stack, like the CPython VM)

Compiler1 way to solve
📤 OUTPUT: return the number (int or float), e.g. 7. Use `return`, not print().
rpn: list of strings: numbers ("2", "2.5") and operators + - * / // % **.
Push numbers (int if possible, else float); for an operator pop b, then a, push a op b.
Not enough values -> raise SyntaxError("stack underflow")
More than one value left at the end -> raise SyntaxError("too many values")
Division by zero -> ZeroDivisionError.      eval_rpn(["1", "2", "3", "*", "+"]) -> 7
Solve “Stage 8 — the Stack Machine (a list used as a stack, like the CPython VM)” in your browser →

← String handling DICTIONARIES (key-value storage) →