Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 17 / Topic 2 of 20

Arrays and strings

Python's list is a dynamic array: one contiguous block of memory that grows as needed. That layout is why nums[i] and append are O(1), and why anything that touches the front — insert(0, x), pop(0) — is O(n): every other item has to shift one slot. Strings are immutable arrays of characters: every "change" quietly builds a new string. Think of a row of numbered lockers: jumping straight to locker 7 is instant, but squeezing a new locker in at the front means re-labelling every locker after it.

Operation Cost Why
nums[i], nums.append(x) O(1) direct slot access; append fills pre-grown space
nums.insert(0, x), nums.pop(0) O(n) everything after the slot shifts
nums[1:] (any slice) O(n) slicing copies — it is a new list, not a view
text += piece in a loop O(n²) overall each += builds a whole new string

Measured (200,000 appends at the end vs a tenth as many inserts at the front):

  200,000 appends at the end:       2.5 ms
  20,000 inserts at the front:    53.0 ms  (varies by machine)

Ten times fewer operations, yet twenty times slower — front inserts shift everything. Build strings with join, not +=:

names = ["Ravi", "Asha", "Imran", "Kavya"]
line = ", ".join(names)            # one O(n) build
print(line)      # Ravi, Asha, Imran, Kavya

A matrix (2D grid) is just a list of rows, and zip(*matrix) regroups it column by column:

sales = [
    [12, 15, 9],     # Kothrud
    [7, 11, 14],     # Baner
    [10, 8, 13],     # Camp
]
print([sum(row) for row in sales])        # [36, 32, 31]  per-shop totals
print([sum(col) for col in zip(*sales)])  # [29, 34, 36]  per-month totals

Real-world example: a sales dashboard holding "three shops Ɨ three months" as a grid answers both "how did Baner do this quarter?" (a row) and "how did March go across shops?" (a column) with the two lines above.

āš ļø A slice is a copy: rest = orders[1:] costs O(n) time and memory, and changing rest never touches orders. That protects you from surprises but silently doubles memory if you slice big lists in a loop.

Practice: row/column totals and transposes on small grids; in-place array edits (remove a value, de-duplicate a sorted list); string building and splitting (join, split, reversing words).

Practice on LeetCode - start here: Remove Duplicates from Sorted Array Ā· Plus One Ā· Length of Last Word Ā· Pascal's Triangle Ā· Rotate Array

Show the full practice list (14 more problems)

Core practice - gentler first:

Stretch - tougher; come back once the core feels comfortable:

Problem Difficulty
Game of Life Medium
Spiral Matrix II Medium
Zigzag Conversion Medium
Text Justification Hard

Full program: examples/02_arrays_strings.py.

Exercise 2: Arrays and strings — sales grid report

Scenario: A three-shop chain tracks three months of sales in a grid (rows = shops, columns = months) and wants shop totals, month totals, and a one-line report. What to do: Write shop_totals(sales) (sum of each row), month_totals(sales) (sum of each column — zip(*sales) regroups the grid column by column), and report_line(shops, totals) that builds "Kothrud=36, Baner=32, Camp=31" with one ", ".join(...) — no += string building in a loop. Print all three.

Starting data:

SALES = [
    [12, 15, 9],     # Kothrud
    [7, 11, 14],     # Baner
    [10, 8, 13],     # Camp
]
SHOPS = ["Kothrud", "Baner", "Camp"]

Sample output:

Shop totals: [36, 32, 31]
Month totals: [29, 34, 36]
Report: Kothrud=36, Baner=32, Camp=31
Show the solution to Exercise 2
"""Exercise 2: Arrays and strings - sales grid report.

Row totals come from summing each row; month totals come from
zip(*grid), which regroups the grid column by column. The report line
is built once with join - no += string building in a loop.

Run:   python ex02.py   (macOS/Linux: python3 ex02.py)
"""

SALES = [
    [12, 15, 9],     # Kothrud
    [7, 11, 14],     # Baner
    [10, 8, 13],     # Camp
]
SHOPS = ["Kothrud", "Baner", "Camp"]


def shop_totals(sales: list[list[int]]) -> list[int]:
    return [sum(row) for row in sales]


def month_totals(sales: list[list[int]]) -> list[int]:
    return [sum(column) for column in zip(*sales)]


def report_line(shops: list[str], totals: list[int]) -> str:
    return ", ".join(f"{shop}={total}" for shop, total in zip(shops, totals))


def main() -> None:
    totals = shop_totals(SALES)
    print(f"Shop totals: {totals}")
    print(f"Month totals: {month_totals(SALES)}")
    print(f"Report: {report_line(SHOPS, totals)}")


if __name__ == "__main__":
    main()

šŸ’” Hint: zip(*sales) yields (12, 7, 10), then (15, 11, 8), then (9, 14, 13) — one tuple per column.

Search the guide