DEV Community

Cover image for Python Data Structures
Alex Murithi
Alex Murithi

Posted on

Python Data Structures

Python Data Structures: Lists, Tuples, Dictionaries, and Sets

Python’s built‑in data structures are the foundation for organizing and manipulating data.

1. Lists - Ordered and Mutable

A list is like a container that can hold multiple items in order. You can add, remove, or change elements at any time. Lists are flexible and widely used for tasks where data changes frequently.

students = ['Bob', 'Faith', 'Brian', 'Ken']   # Strings
scores = [78, 85, 67, 34]                     # Integers
prices = [125.5, 250.0, 85.75]                # Floats
mixed = ['Amina', 24, True, 3.14]             # Mixed types
nested = [[1,2,3], [4,5,6], [7,8,9]]          # List of lists

print(students)
print(scores)
print(prices)
print(mixed)
print(nested)
Enter fullscreen mode Exit fullscreen mode

Output

['Bob', 'Faith', 'Brian', 'Ken']
[78, 85, 67, 34]
[125.5, 250.0, 85.75]
['Amina', 24, True, 3.14]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Enter fullscreen mode Exit fullscreen mode

Why Lists Matter
Lists are perfect for storing collections of items where order matters -like student names, daily scores, or shopping carts.

2. Tuples - Ordered and Immutable

A tuple looks like a list but cannot be changed after creation. This immutability makes tuples reliable for fixed data such as coordinates, RGB values, or days of the week.

nairobi_coord = (1.2864, 36.8172)
days = ('Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun')

print(nairobi_coord[0])   # Latitude
print(days[-1])           # Sunday
print(days[1:4])          # Tue, Wed, Thur
Enter fullscreen mode Exit fullscreen mode

Output

1.2864
Sun
('Tue', 'Wed', 'Thur')
Enter fullscreen mode Exit fullscreen mode

Why Tuples Matter
Tuples are useful when you want to ensure data stays constant. For example, in a mapping project, you store GPS coordinates in tuples to avoid accidental changes during calculations.

3. Dictionaries - Key‑Value Pairs

A dictionary stores data in key‑value pairs. Instead of accessing items by position, you use a key. This makes dictionaries ideal for structured data like user profiles, product catalogs, or JSON responses.

student = {
    "name": "Amina Wanjiku",
    "age": 24,
    "track": "Data Science",
    "scores": [78, 85, 91],
    "active": True
}

print(student["name"])          # Direct access
print(student.get("age"))       # Safe access
print(student.get("city", "Not found"))
print(student["scores"][0])     # Nested access
Enter fullscreen mode Exit fullscreen mode

Output

Amina Wanjiku
24
Not found
78
Enter fullscreen mode Exit fullscreen mode

Why Dictionaries Matter
Dictionaries are powerful for fast lookups and structured data. In a payroll automation script, you can use dictionaries to store employee details, with IDs as keys and salary/department as values - making retrieval and updates efficient.

4. Sets - Unique and Unordered

A set stores unique items. Duplicates are automatically removed, and order is not guaranteed. Sets are great for deduplication and membership tests.

cities = {"Nairobi", "Mombasa", "Kisumu", "Nairobi"}
print(cities)          # {'Nairobi', 'Mombasa', 'Kisumu'}
print(len(cities))     # 3

tags = ["Python", "data", "python", "sql", "data"]
unique_tags = set(tags)
print(unique_tags)     # {'Python', 'data', 'sql'}
Enter fullscreen mode Exit fullscreen mode

Set Operations
Sets support mathematical operations like union, intersection, and difference.

ds_students = {"Hope", "Brian", "Otieno", "Njeri"}
de_students = {"Njeri", "Otieno", "Kamau", "Aisha"}

print(ds_students & de_students)  # Intersection
print(ds_students | de_students)  # Union
print(ds_students - de_students)  # Difference
print(ds_students ^ de_students)  # Symmetric difference
Enter fullscreen mode Exit fullscreen mode

Output

{'Otieno', 'Njeri'}
{'Hope', 'Brian', 'Otieno', 'Njeri', 'Kamau', 'Aisha'}
{'Hope', 'Brian'}
{'Hope', 'Brian', 'Kamau', 'Aisha'}
Enter fullscreen mode Exit fullscreen mode

Why Sets Matter
In a data‑cleaning pipeline, they are used to remove duplicate email addresses before sending notifications - ensuring each user received only one message.

Real‑World Example: Mini Inventory System

products = {
    'Sugar': {'price': 120, 'stock': 50},
    'Rice': {'price': 200, 'stock': 30},
    'Beans': {'price': 150, 'stock': 0}
}

# List of items to restock
restock_list = [item for item, info in products.items() if info['stock'] == 0]

# Tuple for supplier info
supplier = ('AgroSupplies Ltd', 'Nairobi')

# Set of unique categories
categories = {'Food', 'Grains', 'Food'}  # duplicates removed

print(f"Restock items: {restock_list}")
print(f"Supplier: {supplier[0]} located in {supplier[1]}")
print(f"Categories: {categories}")
Enter fullscreen mode Exit fullscreen mode

Output

Restock items: ['Beans']
Supplier: AgroSupplies Ltd located in Nairobi
Categories: {'Food', 'Grains'}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Use lists for flexible, ordered data.

Use tuples for fixed, unchangeable data.

Use dictionaries for structured, key‑value mappings.

Use sets for unique, unordered collections.

Top comments (0)