Lists
A list is an ordered collection of values that you can grow, shrink, and rearrange after it's created — the closest thing Python has to an actual grocery list.
Creating a list and reading from it
Square brackets with commas between items make a list. Items are numbered starting at 0, and a negative index counts from the end:
groceries = ["milk", "eggs", "bread", "spinach"] print(groceries[0]) print(groceries[-1]) print(len(groceries))
milk spinach 4
Adding, removing, and changing items
Unlike a string, a list can be changed in place. .append() adds to the end, .remove() deletes the first matching value, and assigning to an index overwrites what's there:
groceries.append("cheese")
groceries.remove("bread")
groceries[0] = "oat milk"
print(groceries)
['oat milk', 'eggs', 'spinach', 'cheese']
Walking through it: append("cheese") tacks cheese on the end, remove("bread") drops bread wherever it was sitting, and groceries[0] = "oat milk" swaps out whatever was first — which by then was still "milk" — for "oat milk".
Slicing out a range of items
The same [start:end] slicing you saw with strings works on lists too, and it always hands back a new list rather than a single value:
numbers = [10, 20, 30, 40, 50] print(numbers[1:3]) print(numbers[:2]) print(numbers[2:])
[20, 30] [10, 20] [30, 40, 50]
Leaving out the start means "from the beginning"; leaving out the end means "through the end."
Sorting and summing
prices = [4.5, 2.0, 6.25, 1.75] prices.sort() print(prices) print(sum(prices))
[1.75, 2.0, 4.5, 6.25] 14.5
.sort() rearranges the list itself and gives back nothing useful (don't write prices = prices.sort() — you'll end up with None). If you'd rather keep the original order and get a new sorted list back, use sorted(prices) instead.