← Learning Hub
Beginner

Lists and Tuples

A list stores many values in order, inside square brackets. Lists can be changed: you can add, remove and sort items.

Real programs rarely deal with just one value. A shopping cart has many items, a class has many students, a month has many sales. Instead of making item1, item2, item3..., you keep them all in one list. A list keeps the order you put things in, and it can hold duplicates.

Lists are like a numbered shelf: each item has a position (starting at 0), and you can add, remove or rearrange items whenever you want.

Example
You can edit this code.

Sorting and simple maths

Example
You can edit this code.

Python has built-in helpers that work on whole lists: min, max, sum and len. You don't need to write a loop for these common jobs. Note that sort() changes the list itself - after sorting, the original order is gone.

Tuples

A tuple is like a list but cannot be changed. Use round brackets. Good for values that belong together, like a location.

Why have something that can't change? Because it's safer. A tuple tells anyone reading your code: "these values belong together and must stay as they are" - like the latitude and longitude of a shop, or the date parts (year, month, day). Python can also use tuples as dictionary keys, which lists can't be.

Example
You can edit this code.
Use sorted(prices) to get a new sorted list and keep the original as it was.
Key points
  • Lists hold many values in order and can be changed: append, remove, sort.
  • len, min, max, sum work on whole lists.
  • Tuples are fixed lists in round brackets; unpack them with a, b = pair.

📝 Test yourself

1. Which method adds an item to the end of a list?
2. What is the main difference between a list and a tuple?
3. Fill in the function that adds up all numbers in a list:
([1, 2, 3])