Skip to main content

Lists

beginner12 min readLesson 16 of 169

Ordered, mutable collections: append, insert, remove, sort.

A list holds many values in order:

todo = ["email boss", "buy milk", "walk dog"]

Lists are mutable โ€” you can change them in place:

todo[0] = "email boss FIRST"
todo.append("sleep")        # add to the end
todo.insert(1, "coffee")    # insert at position 1
todo.remove("buy milk")     # remove by value
last = todo.pop()           # remove + return the last item

Everyday list tools:

len(todo)          # how many
"buy milk" in todo # membership: True/False
todo.sort()        # order in place
todo.reverse()     # flip in place
sorted(todo)       # NEW sorted list, original untouched

sort() mutates and returns None; sorted() returns a new list. Mixing these two up is a classic beginner bug:

names = sorted(names)   # right
names = names.sort()    # BUG: names becomes None

Slicing works on lists too

Everything from strings โ€” [start:stop], negatives, steps โ€” applies to lists.

Now practice

List DrillsBuild, mutate, and query lists.4 challenges ยท ยท ~30 min