No history yet

Advanced Data Structures

Organizing Your Data

Writing code is about more than just telling the computer what to do. It's also about organizing the information, or data, so your program can work with it efficiently. Python gives you several powerful tools for this, called data structures. Let's move beyond simple variables and look at the four most common ones: lists, tuples, dictionaries, and sets.

Lists: The Versatile Workhorse

Think of a list like a grocery list. It's an ordered collection of items, and you can change it whenever you want. You can add items, remove them, or change the order. In Python, lists are incredibly flexible and are often the default choice for storing a sequence of items.

# A list of Raspberry Pi components
components = ['Raspberry Pi', 'Breadboard', 'LED', 'Resistor']

# Add an item to the end
components.append('Jumper Wires')
print(components)
# Output: ['Raspberry Pi', 'Breadboard', 'LED', 'Resistor', 'Jumper Wires']

# Access an item by its position (index)
# Python indexing starts at 0
first_item = components[0]
print(first_item)
# Output: 'Raspberry Pi'

# Remove a specific item
components.remove('LED')
print(components)
# Output: ['Raspberry Pi', 'Breadboard', 'Resistor', 'Jumper Wires']

You can also grab a portion of a list, a technique called slicing.

# Get items from index 1 up to (but not including) index 3
middle_items = components[1:3]
print(middle_items)
# Output: ['Breadboard', 'Resistor']

Lists are mutable, meaning you can change their contents after they're created. This flexibility is their greatest strength.

Tuples: Data That Doesn't Change

A tuple is like a list, but with one crucial difference: it's immutable. Once you create a tuple, you cannot change it. You can't add, remove, or alter its items. This sounds restrictive, but it's incredibly useful for data that should remain constant, like the coordinates of a point on a map or the days of the week.

# A tuple of RGB color values
red_color = (255, 0, 0)

# Access items just like a list
print(red_color[0])
# Output: 255

# Trying to change an item will cause an error!
# red_color[0] = 200  # This would raise a TypeError

This immutability guarantees that the data won't be accidentally modified elsewhere in your program. It also allows Python to perform some internal optimizations, making tuples slightly faster and more memory-efficient than lists in some cases.

Dictionaries: The Power of Pairs

Imagine a real-world dictionary. You don't find a definition by its page number; you look up a word. Python dictionaries work the same way. They store information in key-value pairs. You provide a unique key to store a value, and you use that same key to get the value back.

# A dictionary describing a Raspberry Pi model
pi_specs = {
    "model": "4 Model B",
    "ram_gb": 8,
    "has_wifi": True
}

# Access a value by its key
print(pi_specs["model"])
# Output: '4 Model B'

# Add a new key-value pair
pi_specs["usb_ports"] = 4

# Change an existing value
pi_specs["ram_gb"] = 4

print(pi_specs)
# Output: {'model': '4 Model B', 'ram_gb': 4, 'has_wifi': True, 'usb_ports': 4}

Dictionaries are perfect for labeling data. Instead of remembering that the item at index 2 is the RAM, you can just ask for the value associated with the "ram_gb" key. It makes your code much more readable and less prone to errors.

Sets: All About Uniqueness

The final major data structure is the set. A set has two defining features: its items are unordered, and it cannot contain duplicate values. If you try to add an item that's already in the set, nothing happens.

# A list with duplicate values
parts_needed = ['resistor', 'led', 'resistor', 'switch']

# Convert the list to a set to get unique items
unique_parts = set(parts_needed)

print(unique_parts)
# Output: {'led', 'resistor', 'switch'}
# Note: the order might be different!

Sets are extremely fast for checking if an item is present. They are also great for performing mathematical set operations, like finding the union (all items from both sets), intersection (items that appear in both sets), and difference (items in one set but not the other).

# Set of components for project A
project_a = {'resistor', 'led', 'capacitor'}

# Set of components for project B
project_b = {'resistor', 'switch', 'motor'}

# Components in either project (union)
all_components = project_a.union(project_b)
print(all_components)
# Output: {'led', 'capacitor', 'motor', 'switch', 'resistor'}

# Components in both projects (intersection)
common_components = project_a.intersection(project_b)
print(common_components)
# Output: {'resistor'}

Choosing the right data structure is a key skill in programming. By understanding the strengths of lists, tuples, dictionaries, and sets, you can write cleaner, more efficient, and more powerful code.

Time to check your understanding.

Quiz Questions 1/6

You need to store a collection of items that can be modified, and you need to maintain the order in which they were added. Which data structure is the most suitable?

Quiz Questions 2/6

Which of the following Python data structures is immutable?

These structures are the building blocks for managing collections of data in almost any Python program you'll write.