Collections
Lists
Lists are Python's general-purpose mutable sequence type. Use them when order matters and the collection may grow, shrink, or be rearranged.
Indexing reads individual positions. 0 is the first item, and negative indexes count backward from the end.
Mutation and copying matter: append() changes the list, while sorted() returns a new ordered list and leaves the original alone.
Create a list with square brackets. Because lists are mutable, append() changes this same list object.
Source
numbers = [3, 1, 4]
numbers.append(1)
print(numbers)Output
[3, 1, 4, 1]Use indexes to read positions. Negative indexes are convenient for reading from the end.
Source
print(numbers[0])
print(numbers[-1])Output
3
1Use sorted() when you want an ordered copy and still need the original order afterward.
Source
print(sorted(numbers))
print(numbers)Output
[1, 1, 3, 4]
[3, 1, 4, 1]Notes
- Lists are mutable sequences: methods such as
append()change the list in place. - Negative indexes count from the end.
sorted()returns a new list;list.sort()sorts the existing list in place.
See also
- related: Tuples
- related: Sets
- related: Slices
- related: Copying Collections
Run the complete example
Expected output
[3, 1, 4, 1]
3
1
[1, 1, 3, 4]
[3, 1, 4, 1]
Execution time appears here after you run the example.