Tutorials / Python from Scratch / Lists and tuples

Lists and tuples

13 min read python
Course contents (15 lessons)
  1. Getting started
  2. Installing Python 3.13 and running your first script
  3. Variables and basic data types
  4. Text, numbers and user input
  5. Working with strings
  6. Numbers and arithmetic
  7. Input and output: talking to the user
  8. Making decisions and repeating work
  9. Making decisions with if, elif and else
  10. Loops: for, while, break and continue
  11. Collections of data
  12. Lists and tuples
  13. Dictionaries and sets
  14. Functions and modules
  15. Writing your own functions
  16. Modules, pip and virtual environments
  17. Files and errors
  18. Reading and writing files
  19. Errors and exceptions
  20. Final project: expense tracker
  21. Project: build the expense tracker, part 1
  22. Project: summaries, search and improvements

One variable, many values

A to-do app does not have one task, it has a list of them. Python's list holds an ordered collection of values. You write it with square brackets and commas.

tasks = ["buy milk", "pay electricity bill", "call the plumber"]

print(tasks[0])          # buy milk
print(tasks[-1])         # call the plumber
print(len(tasks))        # 3

tasks.append("renew passport")
tasks.insert(0, "morning walk")
tasks.remove("buy milk")
done = tasks.pop()       # removes and returns the last item

print(done)              # renew passport
print(tasks)

for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")

Output:

renew passport
['morning walk', 'pay electricity bill', 'call the plumber']
1. morning walk
2. pay electricity bill
3. call the plumber

What happened

Positions start at zero, and negative numbers count from the end, as with strings. append adds to the end. insert(0, x) adds at the front. remove(x) deletes the first item equal to x. pop() removes the last item and gives it back to you. enumerate gives you the position and the value together, which is cleaner than keeping your own counter.

Lists can be changed

Unlike strings, lists are mutable. You can replace an item directly:

tasks[1] = "pay gas bill"

Slicing

Slices work the same way as in strings and give a new list.

nums = [10, 20, 30, 40, 50]
print(nums[1:3])     # [20, 30]
print(nums[:2])      # [10, 20]
print(nums[2:])      # [30, 40, 50]
print(nums[::-1])    # [50, 40, 30, 20, 10]  reversed copy

Handy list tools

ToolWhat it does
len(x)Number of items
sum(x), min(x), max(x)Total, smallest and largest of numbers
x.sort()Sorts the list in place
sorted(x)Returns a new sorted list
x.extend(y)Adds all items of y to x
item in xTrue if the item is present
x.index(item)Position of the first match

A short example with invoice amounts:

amounts = [1200, 450, 3100, 780]
print(sum(amounts))            # 5530
print(max(amounts))            # 3100
print(sorted(amounts))         # [450, 780, 1200, 3100]
print(amounts)                 # original order is unchanged

The copy trap

This is the classic list mistake. Assigning a list to another variable does not copy it. Both names point to the same list.

a = [1, 2, 3]
b = a
b.append(4)
print(a)         # [1, 2, 3, 4]  - a changed too!

c = a.copy()     # or list(a), or a[:]
c.append(5)
print(a)         # [1, 2, 3, 4]  - unchanged

I lost an hour to this once. A function modified a list I passed in, and I could not see why my original data kept changing. If you want an independent copy, ask for one with .copy().

Another common mistake

Methods such as sort() and append() change the list and return None. Writing nums = nums.sort() replaces your list with None. Call nums.sort() on its own line, or use sorted(nums) if you want a result.

Tuples

A tuple is like a list that cannot be changed after you create it. You write it with round brackets.

location = (31.5204, 74.3587)      # latitude, longitude of Lahore
lat, lon = location                # unpacking
print(lat, lon)

# location[0] = 30.0   # TypeError: tuples are immutable

Use a tuple for a small group of values that belong together and should not change, such as coordinates, an RGB colour or a (name, price) pair. Use a list for a collection that grows or shrinks. A one-item tuple needs a trailing comma: (5,). Without the comma, (5) is just the number 5 in brackets.

Lists of lists

Lists can hold other lists, which is useful for tables.

orders = [["Ali", 1200], ["Sara", 450]]
for name, amount in orders:
    print(name, amount)

Try it yourself

Make a list of five numbers representing daily sales. Print the total, the average (total divided by the count), the best day and the worst. Then sort the list from high to low. Hint: sorted(sales, reverse=True). Finally, make a copy of the list, remove the lowest value from the copy, and print both lists to confirm the original did not change.

python
tasks = ["buy milk", "pay electricity bill", "call the plumber"]

print(tasks[0])          # buy milk
print(tasks[-1])         # call the plumber
print(len(tasks))        # 3

tasks.append("renew passport")
tasks.insert(0, "morning walk")
tasks.remove("buy milk")
done = tasks.pop()       # removes and returns the last item

print(done)              # renew passport
print(tasks)

for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account