DEV Community

Cover image for Python Data Structures
Emilio Ochieng
Emilio Ochieng

Posted on Edited on

Python Data Structures

Python has four built-in structures for holding collections of data, and each one exists because it makes a different trade-off between order, mutability, and uniqueness.

Lists

A list is an ordered, mutable (changeable) collection, written with square brackets. Items can be added, removed, or changed after creation, and duplicates are allowed.

fruits = ["apple", "banana", "apple", "mango"]
fruits.append("orange")
fruits[0] = "pineapple"
print(fruits)   # ['pineapple', 'banana', 'apple', 'mango', 'orange']
Enter fullscreen mode Exit fullscreen mode

Tuples

A tuple is an ordered, immutable (unchangeable) collection, written with parentheses. Once created, its contents can't be modified - no adding, removing, or changing items.

coordinates = (36.8219, -1.2921)
# coordinates[0] = 40   # this would raise an error - tuples can't be modified
Enter fullscreen mode Exit fullscreen mode

Dictionaries

A dictionary stores data as key-value pairs, written with curly braces. Instead of accessing items by position (like a list), you access them by a unique key - which makes lookups fast and the data self-describing.

customer = {
    "name": "Emilio ochieng",
    "city": "Nairobi",
    "loyalty_points": 120
}

print(customer["name"])       # Emilio ochieng
customer["loyalty_points"] += 10
Enter fullscreen mode Exit fullscreen mode

Sets

A set is an unordered collection of unique items - duplicates are automatically removed, and there's no guaranteed order to how items are stored.

cities = {"Nairobi", "Nakuru", "Nairobi", "Mombasa"}
print(cities)   # {'Nairobi', 'Nakuru', 'Mombasa'} - the duplicate is gone
Enter fullscreen mode Exit fullscreen mode

Sets are particularly useful for membership checks ("Nairobi" in cities) and for operations like finding what two collections have in common:

supported_cities = {"Nairobi", "Nakuru", "Mombasa"}
customer_cities = {"Nakuru", "Eldoret"}

print(supported_cities & customer_cities)   # {'Nakuru'} - intersection
Enter fullscreen mode Exit fullscreen mode

When to use each

Structure Ordered? Mutable? Duplicates? Use it when...
List Yes Yes Allowed You need a sequence you'll modify — adding, removing, reordering items
Tuple Yes No Allowed The data shouldn't change — fixed coordinates, a date (year, month, day)
Dictionary Insertion order (3.7+) Yes Keys must be unique You need to look things up by a meaningful label rather than position
Set No Yes Not allowed You need uniqueness enforced, or fast membership checks

Practical examples

Modeling something like a single row from the Sunrise Supermarket products table as a dictionary - it maps naturally onto named fields the way a database row does:

product = {
    "product_id": 1,
    "product_name": "Maize Flour 2kg",
    "category": "Groceries",
    "unit_price": 180.00
}

print(f"{product['product_name']} costs KES {product['unit_price']}")
Enter fullscreen mode Exit fullscreen mode

Using a list of those dictionaries to represent an entire table, and a set to quickly answer "what categories exist?":

products = [
    {"product_name": "Maize Flour 2kg", "category": "Groceries"},
    {"product_name": "Cooking Oil 1L", "category": "Groceries"},
    {"product_name": "Bathing Soap", "category": "Toiletries"},
]

categories = {p["category"] for p in products}
print(categories)   # {'Groceries', 'Toiletries'}
Enter fullscreen mode Exit fullscreen mode

What I understood from this

Choosing between these stopped being confusing once I stopped thinking about syntax (brackets vs. braces vs. parentheses) and started thinking about the rule each one enforces. A list says "order matters, and you're allowed to change your mind." A tuple says "order matters, but this is locked." A dictionary says "forget position - find things by name." A set says "I don't care about order, but I will not tolerate duplicates." Once the question became "which rule does my data actually need," the right structure usually picked itself - a database row, with its named fields, is obviously a dictionary; a fixed set of coordinates that should never change is obviously a tuple.

Top comments (0)