This tutorial will guide you through creating and using Python’s core data structures, including lists, tuples, dictionaries, sets, and more. You’ll learn how to manipulate these structures, apply them in real-world scenarios, and solve problems efficiently.

Beginner30 minutes

Step 1: Step 1: Understanding Lists

Lists are ordered, mutable collections of items. They are one of the most versatile data structures in Python. You can store any type of data in a list, including other lists.

- Creating a List: Use square brackets [].

- Accessing Elements: Use indexing (e.g., list[0]).

- Modifying Lists: Use methods like append(), insert(), and remove().

# Creating a list
fruits = ['apple', 'banana', 'cherry']

# Accessing elements
print(fruits[1])  # Output: banana

# Modifying a list
fruits.append('orange')
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']

Practice Exercise

Create a list of your favorite movies. Add a new movie to the list, remove the least favorite, and print the updated list.

Show Solution
# Create a list of favorite movies
movies = ['Inception', 'The Matrix', 'Interstellar']

# Add a new movie
movies.append('The Dark Knight')

# Remove the least favorite movie
movies.remove('The Matrix')

# Print the updated list
print(movies)  # Output: ['Inception', 'Interstellar', 'The Dark Knight']

Step 2: Step 2: Working with Tuples

Tuples are similar to lists but are immutable, meaning their elements cannot be changed after creation. They are useful for storing fixed data.

- Creating a Tuple: Use parentheses ().

- Accessing Elements: Use indexing (e.g., tuple[0]).

- Immutable Nature: Once created, elements cannot be modified.

# Creating a tuple
coordinates = (10, 20)

# Accessing elements
print(coordinates[0])  # Output: 10

# Trying to modify a tuple (will raise an error)
# coordinates[0] = 15  # TypeError: 'tuple' object does not support item assignment

Practice Exercise

Create a tuple representing a date (year, month, day). Print the month and check if the year is a leap year.

Show Solution
# Create a date tuple
date = (2023, 10, 5)

# Print the month
print(date[1])  # Output: 10

# Check if the year is a leap year
year = date[0]
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f'Is {year} a leap year? {is_leap}')  # Output: Is 2023 a leap year? False

Step 3: Step 3: Exploring Dictionaries

Dictionaries are unordered collections of key-value pairs. They are ideal for storing data that can be quickly retrieved using a unique key.

- Creating a Dictionary: Use curly braces {}.

- Accessing Values: Use keys (e.g., dict['key']).

- Modifying Dictionaries: Add or update key-value pairs.

# Creating a dictionary
student = {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

# Accessing values
print(student['name'])  # Output: Alice

# Modifying a dictionary
student['age'] = 22
student['year'] = 'Senior'
print(student)  # Output: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'year': 'Senior'}

Practice Exercise

Create a dictionary to store information about a book (title, author, year). Add a new key for the genre and update the year. Print the updated dictionary.

Show Solution
# Create a book dictionary
book = {'title': '1984', 'author': 'George Orwell', 'year': 1949}

# Add a new key for genre
book['genre'] = 'Dystopian'

# Update the year
book['year'] = 1950

# Print the updated dictionary
print(book)  # Output: {'title': '1984', 'author': 'George Orwell', 'year': 1950, 'genre': 'Dystopian'}

Step 4: Step 4: Using Sets

Sets are unordered collections of unique elements. They are useful for operations like union, intersection, and difference.

- Creating a Set: Use curly braces {} or set().

- Adding Elements: Use the add() method.

- Set Operations: Use methods like union(), intersection(), and difference().

# Creating a set
fruits = {'apple', 'banana', 'cherry'}

# Adding an element
fruits.add('orange')
print(fruits)  # Output: {'apple', 'banana', 'cherry', 'orange'}

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2))  # Output: {1, 2, 3, 4, 5}

Practice Exercise

Create two sets representing favorite fruits of two friends. Find the common fruits and the unique fruits for each friend.

Show Solution
# Create two sets
friend1_fruits = {'apple', 'banana', 'cherry'}
friend2_fruits = {'banana', 'orange', 'kiwi'}

# Find common fruits
common_fruits = friend1_fruits.intersection(friend2_fruits)
print(f'Common fruits: {common_fruits}')  # Output: Common fruits: {'banana'}

# Find unique fruits for each friend
unique_friend1 = friend1_fruits.difference(friend2_fruits)
unique_friend2 = friend2_fruits.difference(friend1_fruits)
print(f'Unique to Friend 1: {unique_friend1}')  # Output: Unique to Friend 1: {'apple', 'cherry'}
print(f'Unique to Friend 2: {unique_friend2}')  # Output: Unique to Friend 2: {'orange', 'kiwi'}

Step 5: Step 5: Combining Data Structures

In real-world applications, you often need to combine multiple data structures. For example, you might use a list of dictionaries or a dictionary of sets.

- Nested Structures: Lists within dictionaries, dictionaries within lists, etc.

- Accessing Nested Data: Use multiple indices or keys.

# Creating a list of dictionaries
students = [
    {'name': 'Alice', 'grades': [90, 85, 88]},
    {'name': 'Bob', 'grades': [78, 82, 80]}
]

# Accessing nested data
print(students[0]['grades'][1])  # Output: 85

Practice Exercise

Create a dictionary where each key is a student's name and the value is a list of their grades. Calculate the average grade for each student and store it in a new dictionary.

Show Solution
# Create a dictionary of student grades
students_grades = {
    'Alice': [90, 85, 88],
    'Bob': [78, 82, 80]
}

# Calculate average grades
average_grades = {}
for student, grades in students_grades.items():
    average = sum(grades) / len(grades)
    average_grades[student] = average

# Print the average grades
print(average_grades)  # Output: {'Alice': 87.66666666666667, 'Bob': 80.0}

Step 6: Step 6: Advanced Data Structures - Stacks and Queues

Stacks and queues are abstract data types that follow specific rules for adding and removing elements.

- Stacks: Last-In-First-Out (LIFO) structure. Use append() and pop().

- Queues: First-In-First-Out (FIFO) structure. Use deque from the collections module.

# Implementing a stack
stack = []
stack.append('A')
stack.append('B')
print(stack.pop())  # Output: B

# Implementing a queue
from collections import deque
queue = deque()
queue.append('A')
queue.append('B')
print(queue.popleft())  # Output: A

Practice Exercise

Simulate a printer queue using a queue. Add three print jobs, process them in order, and print the remaining jobs after each step.

Show Solution
from collections import deque

# Create a printer queue
printer_queue = deque()

# Add print jobs
printer_queue.append('Document1')
printer_queue.append('Document2')
printer_queue.append('Document3')

# Process print jobs
while printer_queue:
    current_job = printer_queue.popleft()
    print(f'Printing: {current_job}')
    print(f'Remaining jobs: {list(printer_queue)}')

Step 7: Step 7: Real-World Application - Data Analysis

Data structures are essential for data analysis. For example, you might use lists to store data points and dictionaries to store metadata.

- Data Storage: Use lists for raw data and dictionaries for metadata.

- Data Manipulation: Use loops and comprehensions to process data.

# Example: Analyzing sales data
sales_data = [
    {'product': 'A', 'sales': 100},
    {'product': 'B', 'sales': 200},
    {'product': 'C', 'sales': 150}
]

# Calculate total sales
total_sales = sum(item['sales'] for item in sales_data)
print(f'Total Sales: {total_sales}')  # Output: Total Sales: 450

Practice Exercise

Given a list of dictionaries representing employee data (name, department, salary), calculate the total salary for each department and store the results in a dictionary.

Show Solution
# Employee data
employees = [
    {'name': 'Alice', 'department': 'HR', 'salary': 50000},
    {'name': 'Bob', 'department': 'Engineering', 'salary': 70000},
    {'name': 'Charlie', 'department': 'HR', 'salary': 55000}
]

# Calculate total salary by department
department_salaries = {}
for employee in employees:
    dept = employee['department']
    salary = employee['salary']
    if dept in department_salaries:
        department_salaries[dept] += salary
    else:
        department_salaries[dept] = salary

# Print the results
print(department_salaries)  # Output: {'HR': 105000, 'Engineering': 70000}

Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.

Sign in

Click to access the login or register cheese