Collections

Lists

Lists are ordered, mutable collections.

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]
Lists are mutable sequences. .append extends the same list object — no new list is created.

Use indexes to read positions. Negative indexes are convenient for reading from the end.

Source

print(numbers[0])
print(numbers[-1])

Output

3
1

Use 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

See also

Run the complete example

Example code

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.