Skip to content

    Lists & Tuples In Depth

    Python · Beginner

    Definition

    Lists are mutable ordered collections; tuples are immutable ordered collections.

    The most used containers in Python.

    Diagram

    [1, 2, 3](1, 2)a[1:3]

    Flowchart

    CreateIndex and sliceappend / insert / popUnpack tuples

    Example: Slicing and unpacking

    a = [10, 20, 30, 40]
    x, *rest = a
    print(a[1:3], a[::-1], x, rest)

    Output: [20, 30] [40, 30, 20, 10] 10 [20, 30, 40]

    Complexity

    append O(1) · insert(0) O(n) · pop() O(1)

    Key points

    • Slices create copies
    • Use copy.deepcopy for nested lists

    Interview questions

    Why does [[0]*3]*3 cause bugs?

    All rows refer to the same inner list.

    More Python topics