7.2 Python Data Structures

Introduction to Data Structures

Data structures allow you to store and organize data in Python. In this lesson, we'll explore lists, tuples, dictionaries, and sets - the four main built-in data structures in Python.

Why Data Structures Matter

Choosing the right data structure can make your code more efficient, readable, and maintainable.

Lists

Creating Lists

# Empty list
empty_list = []

# List with elements
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

List Operations

# Accessing elements
first_fruit = fruits[0]      # 'apple'
last_fruit = fruits[-1]      # 'cherry'

# Slicing
some_fruits = fruits[1:3]    # ['banana', 'cherry']

# Modifying lists
fruits.append("orange")      # Add to end
fruits.insert(1, "mango")    # Insert at position
fruits.remove("banana")      # Remove element
del fruits[0]               # Remove by index

# List methods
length = len(fruits)         # Get length
fruits.sort()               # Sort in place
fruits.reverse()            # Reverse the list

# List comprehension
squares = [x**2 for x in range(10)]  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Tuples

Tuples are similar to lists but are immutable (cannot be changed after creation).

Working with Tuples

# Creating tuples
empty_tuple = ()
single_item = ("apple",)  # Note the comma
coordinates = (10, 20)

# Accessing elements
x = coordinates[0]  # 10
y = coordinates[1]  # 20

# Unpacking
x, y = coordinates  # x=10, y=20

# Tuples are immutable
# coordinates[0] = 5  # This would raise an error

# Common use cases
def get_dimensions():
    return 1920, 1080

width, height = get_dimensions()

Dictionaries

Dictionaries store key-value pairs and are optimized for fast lookups.

Working with Dictionaries

# Creating dictionaries
empty_dict = {}
student = {
    "name": "John Doe",
    "age": 20,
    "courses": ["Math", "Science", "English"]
}

# Accessing values
name = student["name"]
age = student.get("age")  # Safer access

# Adding/Updating
student["email"] = "john@example.com"
student["age"] = 21

# Removing items
student.pop("email")  # Remove and return value
del student["age"]    # Remove item

# Dictionary methods
keys = student.keys()
values = student.values()
items = student.items()  # Returns key-value pairs

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Sets

Sets are unordered collections of unique elements.

Working with Sets

# Creating sets
empty_set = set()  # {} creates an empty dictionary
fruits = {"apple", "banana", "cherry"}

# Adding elements
fruits.add("orange")
fruits.add("apple")  # No duplicates allowed

# Removing elements
fruits.remove("banana")  # Raises error if not found
fruits.discard("mango")  # No error if not found

# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union
union = set1 | set2  # {1, 2, 3, 4, 5, 6, 7, 8}

# Intersection
intersection = set1 & set2  # {4, 5}

# Difference
diff = set1 - set2  # {1, 2, 3}

# Symmetric Difference
sym_diff = set1 ^ set2  # {1, 2, 3, 6, 7, 8}

Practice Exercises

Exercise 1: List Manipulation

Create a list of numbers from 1 to 10. Then:

  1. Print only the even numbers
  2. Create a new list with each number squared
  3. Find the sum of all numbers in the list
numbers = list(range(1, 11))

# 1. Print even numbers
evens = [x for x in numbers if x % 2 == 0]
print("Even numbers:", evens)

# 2. Square each number
squares = [x**2 for x in numbers]
print("Squares:", squares)

# 3. Sum of all numbers
total = sum(numbers)
print("Sum:", total)

Exercise 2: Dictionary Practice

Create a dictionary to store information about a book with the following keys: title, author, year, and price. Then:

  1. Add a new key-value pair for the number of pages
  2. Update the price with a 10% discount
  3. Print all the book's information in a formatted way
# Create book dictionary
book = {
    "title": "Python Crash Course",
    "author": "Eric Matthes",
    "year": 2019,
    "price": 39.99
}

# 1. Add number of pages
book["pages"] = 544

# 2. Apply 10% discount
book["price"] *= 0.9

# 3. Print formatted information
print(f"""
Book Information:
Title: {book['title']}
Author: {book['author']}
Year: {book['year']}
Pages: {book['pages']}
Price: ${book['price']:.2f}
""")