DEV Community

Cover image for Python Data structures
Gideon Kiprono
Gideon Kiprono

Posted on

Python Data structures

Introduction

When you go to a grocery store, you don't throw eggs, milk, and apples loosely into a single giant box. You instead put the eggs in a carton, the milk in a jug, and the apples in a bag.
In programming, data structures are those containers. They are specialized ways of organizing and storing data in your computer's memory so that you can access, sort, and modify your information efficiently.

1. The Core Four Data Structures

Python has four built-in data structures that handle almost every data organization task you will encounter.

Lists

A list is an ordered, mutable collection of items enclosed in square brackets [], with elements separated by commas.

  • Ordered: Items maintain their position and can be accessed using an index, starting from 0.
  • Mutable: Items can be added, removed, or modified after the list is created.
  • Allows duplicates: A list can contain repeated values.
  • Supports different data types: A list can contain strings, integers, floats, booleans, and other objects.

Code Snippet:


# =====================================
# UNDERSTANDING LISTS IN PYTHON
# =====================================

# 1. Creating a list
shopping_list = ["Milk", "Eggs", "Bread"]

print("Original List:", shopping_list)

# 2. ORDERED - Accessing items using indexes
print("\nFirst Item:", shopping_list[0])
print("Second Item:", shopping_list[1])

# 3. MUTABLE - Adding a new item
shopping_list.append("Butter")
print("\nAfter Adding Butter:", shopping_list)

# 4. MUTABLE - Modifying an existing item
shopping_list[1] = "Cheese"
print("After Replacing Eggs:", shopping_list)

# 5. MUTABLE - Removing an item
shopping_list.remove("Bread")
print("After Removing Bread:", shopping_list)

# 6. ALLOWS DUPLICATES
shopping_list.append("Milk")
print("\nAfter Adding Duplicate Milk:", shopping_list)

# 7. Checking the number of items
print("Total Items:", len(shopping_list))
Enter fullscreen mode Exit fullscreen mode

Output:

list output

Common List Operations in Python

Operation Python Code Purpose
Create items = ["A", "B"] Creates a list.
Access items[0] Gets the first item.
Add items.append("C") Adds an item at the end of the list.
Insert items.insert(1, "C") Inserts an item at a specified index.
Modify items[0] = "D" Changes an existing item.
Remove items.remove("B") Removes the first matching item.
Delete items.pop() Removes and returns the last item.
Count len(items) Returns the number of items in the list.

Key Takeaway: Python uses zero-based indexing, meaning the first item is at position 0, not 1.

Tuples

A tuple is an ordered, immutable collection of items, typically enclosed in parentheses () and separated by commas.

Unlike lists, tuples cannot be modified after creation. This means you cannot add, remove, or replace individual elements within a tuple.

Key characteristics of tuples:

  • Ordered: Elements maintain their position and can be accessed using indexes, starting from 0.
  • Immutable: Elements cannot be added, removed, or reassigned after the tuple is created.
  • Allows duplicates: Tuples can contain repeated values.
  • Supports different data types: A tuple can store strings, integers, floats, and other Python objects.
  • Supports unpacking: Values can be assigned to individual variables.

Code Snippet:


# =====================================
# UNDERSTANDING TUPLES IN PYTHON
# =====================================

# 1. Creating a tuple
# Fixed GPS coordinates (Latitude, Longitude)
nairobi_coords = (-1.218, 36.889)

print("Original Coordinates:", nairobi_coords)

# 2. ORDERED - Accessing elements by index
print("\nLatitude:", nairobi_coords[0])
print("Longitude:", nairobi_coords[1])

# 3. UNPACKING - Assigning values to variables
latitude, longitude = nairobi_coords

print("\nUnpacked Latitude:", latitude)
print("Unpacked Longitude:", longitude)

# 4. IMMUTABLE - Attempting to modify a tuple
try:
    nairobi_coords[0] = -1.300

except TypeError:
    print("\nERROR: Tuples cannot be modified!")

# 5. LENGTH - Counting elements
print("\nTotal Elements:", len(nairobi_coords))
Enter fullscreen mode Exit fullscreen mode

Output:

tuple output

Lists vs Tuples in Python

Feature List [] Tuple ()
Ordered Yes Yes
Mutable Yes No
Allows duplicates Yes Yes
Indexing Yes Yes
Supports different data types Yes Yes
Add/remove elements Yes No
Common use Shopping lists, inventory, changing data Coordinates, fixed configuration values, records

Key Takeaway:

  • Lists: Use when you need an ordered collection of items that can be modified.
  • Tuples: Use when you need an ordered collection whose elements should remain unchanged.

Dictionaries

A dictionary is a mutable collection of data stored in key-value pairs, enclosed in curly braces {}.

Unlike lists and tuples, which primarily access elements using numerical indexes, dictionaries allow you to retrieve values using unique keys.

Each key acts as an identifier that maps to a corresponding value, similar to how a word in a physical dictionary maps to its definition.

Key characteristics of dictionaries:

  • Key-value pairs: Each element consists of a key and its associated value.
  • Mutable: You can add, update, or remove key-value pairs after creation.
  • Unique keys: Duplicate keys are not allowed. Assigning a value to an existing key replaces its previous value.
  • Insertion ordered: Dictionaries preserve the order in which keys are inserted (Python 3.7+).
  • Flexible data types: Values can contain strings, numbers, lists, tuples, or even other dictionaries.
  • Fast lookups: Dictionaries typically provide efficient access to values through their keys.

Code snippet:


# =====================================
# UNDERSTANDING DICTIONARIES IN PYTHON
# =====================================

# 1. Creating a dictionary
user_profile = {
    "username": "dev_alex",
    "age": 28,
    "clearance": "admin",
    "active": True
}

print("Original Profile:", user_profile)

# 2. ACCESSING VALUES USING KEYS
print("\nUsername:", user_profile["username"])
print("Clearance:", user_profile["clearance"])

# 3. SAFE ACCESS USING .get()
print("Department:", user_profile.get("department", "Not Assigned"))

# 4. MUTABLE - Adding a new key-value pair
user_profile["department"] = "Engineering"
print("\nAfter Adding Department:", user_profile)

# 5. MUTABLE - Updating an existing value
user_profile["clearance"] = "super_admin"
print("Updated Clearance:", user_profile["clearance"])

# 6. MUTABLE - Removing a key-value pair
user_profile.pop("age")
print("\nAfter Removing Age:", user_profile)

# 7. CHECKING IF A KEY EXISTS
if "username" in user_profile:
    print("\nUsername exists in the dictionary")

# 8. ITERATING THROUGH KEY-VALUE PAIRS
print("\n--- USER PROFILE DETAILS ---")

for key, value in user_profile.items():
    print(f"{key}: {value}")

# 9. COUNTING KEY-VALUE PAIRS
print("\nTotal Entries:", len(user_profile))
Enter fullscreen mode Exit fullscreen mode

Output:

Dictionary output

Lists vs Tuples vs Dictionaries in Python

Feature List [] Tuple () Dictionary {}
Ordered Yes Yes Yes (insertion order)
Mutable Yes No Yes
Allows duplicates Yes Yes Values: Yes; Keys: No
Access elements Numerical index Numerical index Unique keys
Supports mixed data types Yes Yes Yes
Add/remove elements Yes No Yes
Common use Shopping lists, inventory Coordinates, fixed records User profiles, configurations, structured records

Key takeaway:

  • Dictionaries are ideal when you want to store, organize, and retrieve related information using meaningful keys rather than numerical positions.
  • They are widely used in Python applications, JSON processing, APIs, data engineering, and configuration management.

Sets

A set is an unordered, mutable collection of unique elements, typically enclosed in curly braces {}.

Unlike lists and tuples, sets do not allow duplicate values. If an element appears more than once, Python automatically keeps only one occurrence.

Sets are particularly useful for removing duplicates, checking membership, and performing mathematical operations such as unions, intersections, and differences.

Key characteristics of sets:

  • Unordered: Elements do not have fixed positions or numerical indexes.
  • Mutable: You can add or remove elements after creating a set.
  • Unique elements: Duplicate values are automatically eliminated.
  • No indexing: You cannot access elements using positions such as my_set[0].
  • Hashable elements: Set elements must be hashable, such as integers, strings, or tuples containing hashable values. Lists and dictionaries cannot be direct set elements.
  • Efficient membership testing: Sets are useful for quickly checking whether an item exists in a collection.

Code snippet:


# =====================================
# UNDERSTANDING SETS IN PYTHON
# =====================================

# 1. CREATING A SET
# Duplicate employee ID 101 is automatically removed
unique_ids = {101, 102, 103, 101}

print("Original Set:", sorted(unique_ids))

# 2. MUTABLE - Adding a new element
unique_ids.add(104)
print("\nAfter Adding 104:", sorted(unique_ids))

# 3. UNIQUE ELEMENTS - Adding a duplicate
unique_ids.add(102)
print("After Adding Duplicate 102:", sorted(unique_ids))

# 4. MUTABLE - Removing an element
unique_ids.remove(103)
print("\nAfter Removing 103:", sorted(unique_ids))

# 5. MEMBERSHIP TESTING
if 101 in unique_ids:
    print("\nEmployee ID 101 exists in the system.")

# 6. SET OPERATIONS
morning_shift = {101, 102, 105}
evening_shift = {102, 104, 106}

# UNION - All unique employees across both shifts
print("\nUnion:", sorted(morning_shift | evening_shift))

# INTERSECTION - Employees in both shifts
print("Intersection:", sorted(morning_shift & evening_shift))

# DIFFERENCE - Employees only in the morning shift
print("Difference:", sorted(morning_shift - evening_shift))

# 7. COUNTING UNIQUE ELEMENTS
print("\nTotal Unique IDs:", len(unique_ids))
Enter fullscreen mode Exit fullscreen mode

Output:

Sets output

Note: I used sorted() to display the elements in ascending order, making the output easier to follow. It returns a sorted list without changing the original set. Sets themselves do not guarantee an iteration order.

Comparison of Python Collections

Feature List [] Tuple () Dictionary {} Set {}
Ordered Yes Yes Yes No
Mutable Yes No Yes Yes
Allows Duplicates Yes Yes Keys: No, Values: Yes No
Supports Indexing Yes Yes Key-based access No
Add/Remove Elements Yes No Yes Yes
Common Use Shopping lists, inventory Coordinates, fixed records User profiles, configurations Unique IDs, removing duplicates

Key takeaway: Use sets when you need to store unique values, remove duplicates, perform membership checks efficiently, or compare collections using mathematical set operations.

For example, in data analytics, sets can help identify customers appearing in two datasets, detect unique product IDs, and compare records between different data sources.

2. Cheat Sheet: When to Use Each One

Choosing the right structure keeps your program fast and free of bugs. Use this simple rule of thumb:

Data Structure Best Used For... Example
List [] Collections of data that need to stay in order and might change later. A list of task names in a to-do app.
Tuple () Fixed, read-only data that must stay safe from accidental changes. Days of the week or config settings.
Dictionary {} Complex data that needs descriptive labels for fast lookups. A product page with price, color, and size.
Set {} Finding unique values or running math checks like finding overlaps. Tracking unique visitors to a website.

3. Practical Example: The Event Registration Manager

Let's bring all four data structures together into a single program that manages guest attendance for a tech conference.

Code snippet:

# ------------Event Registration Manager--------------------
# 1. TUPLE: Fixed event information that should never change
EVENT_INFO = ("Global Tech Summit", "Main Arena", "Day 1")

# 2. LIST: The active queue of arriving VIPs (we need order and flexibility)
vip_queue = ["Sarah", "Michael", "David"]
vip_queue.append("Elena")  # A new VIP arrives and is added to the end

# 3. DICTIONARY: Attendee profiles for quick lookup by ticket ID
attendee_profiles = {
    "TK-890": {"name": "Sarah", "type": "VIP", "checked_in": True},
    "TK-432": {"name": "John", "type": "Standard", "checked_in": False},
    "TK-112": {"name": "Michael", "type": "VIP", "checked_in": True}
}

# 4. SET: Tracking unique industries represented (no duplicates allowed!)
industries_present = {"Finance", "Healthcare", "Tech", "Finance"} # 'Finance' is repeated

# --- PROCESSING THE EVENT DATA ---
print(f"--- WELCOME TO THE {EVENT_INFO[0].upper()} ---")
print(f"Location: {EVENT_INFO[1]} | Schedule: {EVENT_INFO[2]}\n")

# Looking up a profile using a Dictionary Key
search_ticket = "TK-890"
guest_name = attendee_profiles[search_ticket]["name"]
print(f"Ticket Lookup: Ticket {search_ticket} belongs to {guest_name}.")

# Displaying the VIP order from our List
print(f"Next VIP in line to speak: {vip_queue[0]}")

# Displaying our Set (Notice how the duplicate 'Finance' is automatically gone)
print(f"Unique industries attending today: {industries_present}")
Enter fullscreen mode Exit fullscreen mode

Output:

event registration

  • Tuple Protection: EVENT_INFO guarantees that nobody can accidentally overwrite the event name or location mid-program.
  • List Flexibility: vip_queue preserves the order of arrivals and lets us pull or add speakers dynamically.
  • Dictionary Speed: attendee_profiles allows us to instantly pull up a specific person's profile using their ticket code without scanning the entire database.
  • Set Cleanliness: industries_present cleans our metadata automatically, ensuring we only see a list of unique industries without any repeating clutter.

Conclusion

Data structures are the architectural backbone of clean code. By mastering lists, tuples, dictionaries, and sets, you no longer just write code instructions—you map out data intentionally. This structural organization is exactly how massive platforms like Spotify manage playlists (lists), handle user accounts (dictionaries), and eliminate duplicate song recommendations (sets).

Top comments (0)