Python Lists

Tutorial 10 of 65 · pythondeck.com Python course

Lists are ordered, mutable sequences. They can store any objects and grow or shrink dynamically. Common operations: indexing, slicing, append, extend, insert, pop, remove, sort, reverse. List comprehensions concisely build new lists.

Lists are ordered, mutable sequences—Python's workhorse for collections that change size. They support indexing, slicing, iteration, and methods like append and sort in amortized O(1) for end operations.

Choosing list vs tuple vs set vs dict depends on whether you need order, mutability, uniqueness, or key-based lookup.

Literals: [1, 2, 3]; list comprehension: [x*2 for x in range(5)].

Methods: append, extend, insert, pop, remove, clear, sort, reverse.

Slicing assigns sublists: lst[1:3] = [9, 10]; copy with lst.copy() or lst[:].

Iteration: for item in lst; index with enumerate(lst).

Membership x in lst is O(n); use a set for frequent lookups.

Lists can hold mixed types but homogeneous lists are easier to maintain.

Sorting: lst.sort() in place vs sorted(lst) returning new list; use key= for custom ordering. Timsort exploits partially ordered data efficiently.

Aliasing: b = a shares the list; b = a.copy() for shallow copy. Nested lists need deepcopy.

Use lists as stacks; use deque for queues. [0]*n repeats references—unsafe for nested mutables.

Using lst = lst.append(x)—append returns None.

Deleting items while iterating forward over the same list.

Using list as default argument in functions (shared mutable default).

Calling sort() when you needed a new sorted copy and mutated the original unexpectedly.

Use comprehensions for simple transforms; switch to a loop when logic branches heavily.

Prefer extend over repeated append in a loop for another iterable.

Choose deque for FIFO queues; use NumPy arrays for numeric bulk data.

Keep list comprehensions readable—two loops or conditions max before extracting a function.

Profile before replacing lists with deque or NumPy—clarity beats micro-optimization on small data.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates basic ops. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: Basic ops
# Run in the REPL or save as a .py file and execute with python.
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.append(5)
nums.sort()
print(nums)

This sample walks through slicing in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: Slicing
# Run in the REPL or save as a .py file and execute with python.
letters = list("abcdefgh")
print(letters[2:6])
print(letters[::2])
letters[1:3] = ["X", "Y", "Z"]
print(letters)

Here is a hands-on illustration of comprehension. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: Comprehension
# Run in the REPL or save as a .py file and execute with python.
squares = [x*x for x in range(10) if x % 2 == 0]
print(squares)

The program below demonstrates list methods. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Lists are mutable sequences with rich methods
nums = [3, 1, 4, 1, 5]  # starter data with duplicate
nums.append(9)  # add to end in O(1) amortized
nums.insert(0, 0)  # insert at front (O(n) cost)
nums.remove(1)  # removes first matching value
print(nums.count(1), nums.index(4))  # count and first index
nums.sort()  # in-place ascending sort
print(nums)  # sorted list
copy = nums.copy()  # shallow copy of list object
copy.reverse()  # mutate copy only
print(nums, copy)  # original order preserved

This sample walks through nested comprehension in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Build a 3x3 multiplication table with nested comps
size = 3  # matrix dimension
table = [[r * c for c in range(1, size + 1)] for r in range(1, size + 1)]
for row in table:  # each row is its own list
    print(row)  # print one row at a time
flat = [cell for row in table for cell in row]  # flatten
print(sum(flat))  # sum of 1..9 products in 3x3 table
evens = [x for x in range(10) if x % 2 == 0]  # filter even
print(evens)  # [0,2,4,6,8]
pairs = list(zip(["a", "b"], [1, 2]))  # parallel iteration
print(pairs)  # [('a',1),('b',2)]

« Python Operators All tutorials Python Tuples »