Skip to content

Module 8 · Python Data Structures — topic 1 of 22

Data structure introduction

A data structure organises many values so a program can store, find and change them efficiently. Meet Python’s four built-in collections (list, tuple, set, dict) and how they differ.

Beginner 12 min read·Lesson 104 of 306 in Python Programming

Learning objectives

  • Explain what a data structure is
  • Compare list, tuple, set and dict by order, mutability and duplicates
  • Pick a structure for simple scenarios

Definition

A data structure organises many values so a program can store, find and change them efficiently. Meet Python’s four built-in collections (list, tuple, set, dict) and how they differ.

Introduction

A single variable holds a single value. Real programs handle many related values: every student in a class, every item in a cart, every word in a document. A data structure is a way of organising such values together so they can be stored, searched and updated as a unit.

Python has four built-in collection types that cover most needs: lists, tuples, sets and dictionaries. This module studies each one in detail.

Why it matters

Choosing the right structure makes code simpler and faster. Checking whether a username is taken is instant with a set but slow with a long list; looking up a price by product name is natural with a dictionary but awkward with two parallel lists. Good programmers choose structures deliberately.

Detailed explanation

A collection is a value that contains other values, called elements or items. Collections can hold values of any type, including other collections.

Ordered collections (lists and tuples) keep items in a fixed sequence and allow access by position. Dictionaries also remember insertion order. Sets have no order.

Mutable collections (lists, sets and dictionaries) can be changed after creation. Tuples are immutable.

Sets and dictionary keys don’t allow duplicates; lists and tuples do.

TypeLiteralOrderedMutableDuplicatesAccess by
list[1, 2, 3]yesyesallowedindex
tuple(1, 2, 3)yesnoallowedindex
set{1, 2, 3}noyesnot allowedmembership only
dict{"a": 1}insertion orderyeskeys uniquekey

All four support len(), in and iteration with for. Each has its own methods suited to its purpose.

Beyond the built-ins, the standard library adds specialised structures such as deque, Counter and defaultdict (Module 15), and Module 18 builds stacks and queues.

Syntax

Python
marks = [72, 88, 91]
point = (12.5, 77.3)
tags = {"python", "beginner"}
prices = {"tea": 20, "coffee": 35}
  • Square brackets make a list.
  • Parentheses (with commas) make a tuple.
  • Braces with single values make a set.
  • Braces with key: value pairs make a dict.

Code examples

The four collections

Python
marks = [72, 88, 91, 88]
point = (12.5, 77.3)
tags = {"python", "beginner", "python"}
prices = {"tea": 20, "coffee": 35}
for c in (marks, point, tags, prices):
print(type(c).__name__, len(c))
Output
list 4
tuple 2
set 2
dict 2

Shared operations

Python
marks = [72, 88, 91]
prices = {"tea": 20, "coffee": 35}
print(88 in marks, "tea" in prices)
print(max(marks), sorted(prices))
Output
True True
91 ['coffee', 'tea']

More examples

One problem, the right structure for each part

Python
orders = [
("Asha", "pen", 2),
("Ben", "pad", 1),
("Asha", "ink", 3),
]
prices = {"pen": 12, "pad": 60, "ink": 45}
customers = set()
bills = {}
for name, item, qty in orders:
customers.add(name)
bills[name] = bills.get(name, 0) + prices[item] * qty
print("Customers:", sorted(customers))
print("Bills:", bills)
Output
Customers: ['Asha', 'Ben']
Bills: {'Asha': 159, 'Ben': 60}

Step-by-step explanation

  • orders is a list because order and duplicates matter; each order is a fixed tuple of three fields.
  • prices is a dict so each item’s price can be looked up by name.
  • customers is a set, so Asha is recorded only once however many orders she places.
  • bills is a dict that accumulates a total per customer.

Expected output

Running “One problem, the right structure for each part” prints exactly:

TextOutput
Customers: ['Asha', 'Ben']
Bills: {'Asha': 159, 'Ben': 60}

Practical applications

  • Shopping carts are lists of items; product catalogues are dictionaries keyed by product ID.
  • Social apps store followers in sets so duplicates are impossible.
  • GPS coordinates are stored as tuples because a point never changes.

Best practices

  • Choose the structure by how you will access the data.
  • Use tuples for fixed records and lists for growing sequences.
  • Use sets for membership and uniqueness, dicts for lookups by key.

Common mistakes

Using parallel lists instead of a dictionary

Avoid

names = ["tea", "coffee"]
prices = [20, 35]

Prefer

prices = {"tea": 20, "coffee": 35}

Parallel lists drift out of sync when one is changed; a dictionary keeps each pair together.

Expecting a set to keep order

Avoid

print({3, 1, 2}) # assuming 3 1 2

Prefer

print(sorted({3, 1, 2}))

Sets have no defined order; sort them when order matters.

Key takeaways

  • Python’s built-in collections are list, tuple, set and dict.
  • They differ in order, mutability, duplicates and how items are accessed.
  • All support len(), in and for loops.

Try it yourself

  1. 1
    Pick the best structure for: a phone book, the days of the week, unique visitors to a site, a to-do list. Explain each choice.
  2. 2
    Create one example of each collection type and print its type and length.

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