Skip to content
Module 03 of 1250 min readBeginner

Lists, tuples, dicts, sets

The four built-in collections, when each one is right, and how to convert between them.

25%

Listen along

Read “Lists, tuples, dicts, sets” aloud

Plays in your browser using on-device text-to-speech — nothing leaves the page.

Learning objectives

By the end of this module, you should be able to:

  • 01Choose between list, tuple, dict, and set based on the access pattern your code needs
  • 02Slice and index lists, including negative indices and step slicing
  • 03Iterate over dictionaries using .items(), .keys(), .values() correctly
  • 04Use sets for fast membership testing and mathematical operations (union, intersection, difference)

Python has four main built-in collection types. Knowing when each one is right — and how to convert between them — is the single most leveraged knowledge in everyday Python.

list — ordered, mutable, the workhorse

python
rates = [0.07, 0.08, 0.085, 0.10, 0.125]
rates.append(0.13) # add to the end
rates[0] # 0.07 (zero-indexed)
rates[-1] # 0.13 (last item)
rates[1:3] # [0.08, 0.085] (slice)
rates.sort() # sorts in place
len(rates) # 6

Lists are the default sequence type. Use them whenever order matters and you might add or remove items.

tuple — ordered, immutable

Tuples look like lists but cannot be modified after creation. Use them for fixed records (a coordinate, a (date, value) pair) and as dictionary keys (which lists cannot be).

python
point = (3.14, 2.71)
x, y = point # tuple unpacking
x, y = y, x # swap, the Pythonic way
# Returning multiple values
def stats(xs):
return min(xs), max(xs), sum(xs) / len(xs)
lo, hi, mean = stats([1, 2, 3, 4, 5])

dict — key-value mapping

Dictionaries store key→value associations with O(1) lookup. The most common data structure after lists.

python
shares = {'equity': 0.4, 'fixed_income': 0.5, 'cash': 0.1}
shares['equity'] # 0.4
shares['property'] = 0.05 # add a key
'cash' in shares # True
for asset, weight in shares.items():
print(f'{asset}: {weight:.0%}')

set — unordered collection of unique values

Sets are useful when you want fast membership testing or to deduplicate a list. They support mathematical operations (union, intersection, difference).

python
tier_1 = {'KCB', 'Equity', 'Coop', 'NCBA', 'Stanbic'}
tier_2 = {'Family', 'Coop', 'Sidian', 'Equity'}
tier_1 & tier_2 # {'Equity', 'Coop'} (intersection)
tier_1 | tier_2 # union
tier_1 - tier_2 # {'KCB', 'NCBA', 'Stanbic'} (difference)

When to use which

List: ordered, mutable — your default. Tuple: small fixed record, dict key. Dict: key→value lookup. Set: deduplication, fast membership tests. If you find yourself iterating a list to check membership, use a set instead — O(n) becomes O(1).

Exercise

Create a dict mapping three Kenyan asset classes to portfolio weights — equities 40%, fixed income 50%, cash 10%. Then print each line as 'Asset: 40%'.

Key takeaways

  • List = ordered + mutable (default). Tuple = ordered + immutable (use as dict key or fixed record)
  • Dict = key→value, O(1) lookup, the most common structure after lists
  • Set = unique values, fast membership, mathematical operations — O(1) `in` testing
  • If you iterate a list to check membership, use a set instead — O(n) becomes O(1)

Further reading

  1. 01
  2. 02

    Fluent Python, Chapters 2-3

    Luciano Ramalho · O'Reilly · 2022

  3. 03

    Python Cookbook

    David Beazley & Brian K. Jones · O'Reilly · 2013

Loading progress…
LeadAfrikPublic Economics Hub