How to use lists

Create and access a list

Lists are ordered, mutable collections. They may contain repeated values and mixed types, though consistent item types are usually easier to manage.

colors = ["red", "green", "blue"]
print(colors[0])
print(colors[-1])
print(colors[1:])

Add and update items

append() adds one item, while extend() adds each item from another iterable.

colors = ["red"]
colors.append("green")
colors.extend(["blue", "gold"])
colors[0] = "crimson"
print(colors)

Remove and search

remove() deletes the first matching value and fails if absent. pop() removes and returns an indexed item.

tasks = ["email", "code", "test"]
tasks.remove("email")
finished = tasks.pop(0)
print(finished)
print("test" in tasks)

Sort without surprises

sort() changes a list in place. sorted() accepts any iterable and returns a new list, preserving the original.

scores = [8, 3, 10, 5]
ascending = sorted(scores)
scores.sort(reverse=True)
print(ascending)
print(scores)