Python ยท Chapter 15 of 45
Python Lists
A list is an ordered, mutable collection created with `[]`. Lists can hold items of ANY type, including other lists.
Access with `mylist[i]`, slice with `mylist[a:b]`, add with `append()`, remove with `remove()` or `pop()`.
Common methods
`append(x)`, `insert(i, x)`, `remove(x)`, `pop(i)`, `sort()`, `reverse()`, `len(list)`, `x in list`.
Mutability
Lists are mutable, so methods change them in place. Sorting returns None but modifies the list.
Example 1 (python)
nums = [3, 1, 4, 1, 5]
nums.append(9)
nums.sort()
print(nums)Output
[1, 1, 3, 4, 5, 9]Add then sort in place.
Example 2 (python)
colors = ["red", "green", "blue"]
print(colors[0], colors[-1])
print(colors[1:])Output
red blue
['green', 'blue']Indexing and slicing lists.
Key points
- Ordered, mutable, allow duplicates.
- Any type of item, mixed types OK.
- Access with `[i]`, slice with `[a:b]`.
- `append`, `pop`, `sort`, `reverse` modify in place.
๐ก Note: `sorted(list)` returns a NEW sorted list. `list.sort()` sorts in place and returns None.
