Skip to content

Module 8 · Python Data Structures — topic 22 of 22

Choosing appropriate data structures

Decide between list, tuple, set and dictionary by asking how data will be accessed and changed. Compare their strengths, speed of common operations and typical combinations in real programs.

Intermediate 14 min read·Lesson 125 of 306 in Python Programming

Learning objectives

  • Choose a structure from the access pattern
  • Compare operation speed for lists, sets and dicts
  • Combine structures to model real problems

Definition

Decide between list, tuple, set and dictionary by asking how data will be accessed and changed. Compare their strengths, speed of common operations and typical combinations in real programs.

Introduction

Most problems can be solved with any collection, but one choice usually makes the code shorter, clearer and faster. The trick is to ask a few questions about how the data will be used before you choose.

Why it matters

Choosing well early prevents painful rewrites. A program that checks membership in a list of a million items may take seconds where a set takes microseconds, and a dictionary can replace whole loops of searching.

Detailed explanation

Ask: Does order matter? Will items be added or removed? Are duplicates allowed? How will I find an item: by position, by membership or by a key?

NeedChoose
Ordered sequence that changeslist
Fixed record or multiple return valuestuple
Unique items, fast membership, set algebraset
Look up values by keydict
Count occurrencesdict (or collections.Counter)
Group items by a propertydict of lists
Table of recordslist of dicts or list of tuples

Speed of x in collection: list and tuple check items one by one, so the time grows with size; set and dict use hashing, so the time stays roughly constant.

Adding at the end of a list is fast; inserting or removing at the front of a long list is slow. Dictionaries and sets add and remove quickly anywhere.

Memory: tuples are slightly smaller than lists; sets and dicts use more memory in exchange for fast lookups.

Combining structures is normal: a dictionary of student records, each with a list of marks; a set of seen IDs alongside a list that keeps order.

When in doubt, start with the simplest structure that matches the access pattern, and measure if performance matters.

Syntax

Python
orders = [] # sequence that grows
point = (x, y) # fixed record
seen = set() # uniqueness
prices = {} # lookup by key
groups = {key: [] for key in keys}
  • Match the structure to how you will access the data.
  • Combine structures freely.
  • Comments can record why a structure was chosen.

Code examples

Same question, different structures

Python
names_list = ["Asha", "Ben", "Chen"]
names_set = set(names_list)
ages = {"Asha": 21, "Ben": 19, "Chen": 22}
print("Ben" in names_list, "Ben" in names_set, "Ben" in ages)
print(ages["Chen"])
Output
True True True
22

Measuring membership speed

Python
import time
items_list = list(range(200_000))
items_set = set(items_list)
start = time.perf_counter()
for _ in range(200):
199_999 in items_list
list_time = time.perf_counter() - start
start = time.perf_counter()
for _ in range(200):
199_999 in items_set
set_time = time.perf_counter() - start
print("set faster:", set_time < list_time)
Output
set faster: True

Exact times vary by computer, but the set lookup is consistently far faster for large collections.

More examples

Modelling a small library

Python
books = {
"B1": ("Python Basics", "Rao"),
"B2": ("Data with Python", "Iyer"),
"B3": ("Algorithms", "Sen"),
}
borrowed = {}
waitlist = {"B1": ["Ben"]}
members = {"Asha", "Ben", "Chen"}
def borrow(member, book_id):
if member not in members:
return "unknown member"
if book_id in borrowed:
waitlist.setdefault(book_id, []).append(member)
return f"waitlisted for {books[book_id][0]}"
borrowed[book_id] = member
return f"borrowed {books[book_id][0]}"
print(borrow("Asha", "B1"))
print(borrow("Chen", "B1"))
print(borrow("Zoe", "B2"))
print("Borrowed:", borrowed)
print("Waitlist:", waitlist)
Output
borrowed Python Basics
waitlisted for Python Basics
unknown member
Borrowed: {'B1': 'Asha'}
Waitlist: {'B1': ['Ben', 'Chen']}

Step-by-step explanation

  • books is a dict for lookup by ID; each value is a fixed (title, author) tuple.
  • members is a set because only membership matters.
  • borrowed maps a book ID to the member who has it.
  • waitlist is a dict of lists because order of waiting matters.
  • borrow() uses each structure for what it does best.

Expected output

Running “Modelling a small library” prints exactly:

TextOutput
borrowed Python Basics
waitlisted for Python Basics
unknown member
Borrowed: {'B1': 'Asha'}
Waitlist: {'B1': ['Ben', 'Chen']}

Practical applications

  • Web frameworks store request headers in dictionaries and routes in lists.
  • Recommendation systems use sets for fast “already seen” checks.
  • Data pipelines hold rows as lists of dictionaries before saving them.

Best practices

  • Ask how the data will be accessed before choosing.
  • Combine structures to fit each part of a problem.
  • Measure before optimising, but avoid obviously slow patterns.

Common mistakes

Searching a list for lookups

Avoid

for name, price in price_list:
if name == item:
found = price

Prefer

found = prices[item]

A dictionary lookup replaces the whole search loop.

Using a list for uniqueness checks on large data

Avoid

if email not in emails_list:
emails_list.append(email)

Prefer

if email not in emails_set:
emails_set.add(email)

Membership tests on a large list get slower as it grows.

Key takeaways

  • Lists for ordered sequences, tuples for fixed records, sets for uniqueness, dicts for lookups.
  • Set and dict membership is fast; list membership grows with size.
  • Real programs combine several structures.

Try it yourself

  1. 1
    Choose and justify structures for a quiz app: questions, the user’s answers, unique topics covered and scores by topic.
  2. 2
    Rewrite a loop that searches a list of (code, name) pairs into a dictionary lookup.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

13 questions cover the “Python Data Structures” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module