6.1 Organizing Multiple Pieces of Data

In the previous tutorial, you learned about variables and basic data types like strings, integers, floats, and booleans. These are great for storing single values, but what if you need to store multiple related items? That’s where data structures come in!

This tutorial will cover two essential Python data structures: - Lists: Ordered collections you can modify - Dictionaries: Key-value pairs for storing related data

6.2 Lists: Ordered Collections

A list is an ordered collection of items that you can modify. Think of it as a numbered container where each item has a position (index).

Creating Lists

You create lists using square brackets [] with items separated by commas:

# Empty list
empty_list = []

# List of numbers
numbers = [1, 2, 3, 4, 5]

# List of strings
fruits = ["apple", "banana", "cherry"]

# List with mixed types
mixed = [1, "hello", 3.14, True]

print(numbers)
print(fruits)
print(mixed)
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]

Accessing List Elements

Lists are indexed starting from 0. You access elements using square brackets:

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Access by positive index (from start)
print(f"First fruit: {fruits[0]}")
print(f"Second fruit: {fruits[1]}")
print(f"Third fruit: {fruits[2]}")

# Access by negative index (from end)
print(f"Last fruit: {fruits[-1]}")
print(f"Second to last: {fruits[-2]}")
First fruit: apple
Second fruit: banana
Third fruit: cherry
Last fruit: elderberry
Second to last: date

List Slicing

You can extract portions of a list using slicing [start:end]:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get elements from index 2 to 5 (excludes 5)
print(f"numbers[2:5]: {numbers[2:5]}")

# Get first 3 elements
print(f"numbers[:3]: {numbers[:3]}")

# Get elements from index 5 to end
print(f"numbers[5:]: {numbers[5:]}")

# Get every second element
print(f"numbers[::2]: {numbers[::2]}")

# Reverse a list
print(f"numbers[::-1]: {numbers[::-1]}")
numbers[2:5]: [2, 3, 4]
numbers[:3]: [0, 1, 2]
numbers[5:]: [5, 6, 7, 8, 9]
numbers[::2]: [0, 2, 4, 6, 8]
numbers[::-1]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

6.3 List Operations: Adding Elements

Lists are mutable, meaning you can change them after creation. Here are ways to add elements:

append() - Add to End

fruits = ["apple", "banana"]
print(f"Original list: {fruits}")

fruits.append("cherry")
print(f"After append: {fruits}")

fruits.append("date")
print(f"After another append: {fruits}")
Original list: ['apple', 'banana']
After append: ['apple', 'banana', 'cherry']
After another append: ['apple', 'banana', 'cherry', 'date']

insert() - Add at Specific Position

colors = ["red", "blue", "green"]
print(f"Original: {colors}")

# Insert "yellow" at index 1
colors.insert(1, "yellow")
print(f"After insert: {colors}")
Original: ['red', 'blue', 'green']
After insert: ['red', 'yellow', 'blue', 'green']

extend() - Add Multiple Elements

list1 = [1, 2, 3]
list2 = [4, 5, 6]

print(f"list1 before extend: {list1}")
list1.extend(list2)
print(f"list1 after extend: {list1}")

# Alternative: using + operator
list3 = [7, 8, 9]
combined = list1 + list3
print(f"Combined list: {combined}")
list1 before extend: [1, 2, 3]
list1 after extend: [1, 2, 3, 4, 5, 6]
Combined list: [1, 2, 3, 4, 5, 6, 7, 8, 9]

6.4 List Operations: Removing Elements

remove() - Remove by Value

fruits = ["apple", "banana", "cherry", "banana"]
print(f"Original: {fruits}")

# Remove first occurrence of "banana"
fruits.remove("banana")
print(f"After remove: {fruits}")
Original: ['apple', 'banana', 'cherry', 'banana']
After remove: ['apple', 'cherry', 'banana']

pop() - Remove by Index

numbers = [10, 20, 30, 40, 50]
print(f"Original: {numbers}")

# Remove and return last element
last = numbers.pop()
print(f"Popped: {last}")
print(f"After pop: {numbers}")

# Remove and return element at index 1
second = numbers.pop(1)
print(f"Popped at index 1: {second}")
print(f"After pop(1): {numbers}")
Original: [10, 20, 30, 40, 50]
Popped: 50
After pop: [10, 20, 30, 40]
Popped at index 1: 20
After pop(1): [10, 30, 40]

clear() - Remove All Elements

items = [1, 2, 3, 4, 5]
print(f"Before clear: {items}")

items.clear()
print(f"After clear: {items}")
Before clear: [1, 2, 3, 4, 5]
After clear: []

6.5 List Operations: Other Useful Methods

Length, Count, and Index

numbers = [1, 2, 3, 2, 4, 2, 5]

# Get length
print(f"Length: {len(numbers)}")

# Count occurrences
print(f"Count of 2: {numbers.count(2)}")

# Find index of first occurrence
print(f"Index of 3: {numbers.index(3)}")
Length: 7
Count of 2: 3
Index of 3: 2

Sorting and Reversing

# sort() - Sort in place
numbers = [3, 1, 4, 1, 5, 9, 2]
print(f"Original: {numbers}")

numbers.sort()
print(f"After sort: {numbers}")

numbers.sort(reverse=True)
print(f"Sorted descending: {numbers}")

# sorted() - Return new sorted list
original = [5, 2, 8, 1]
sorted_list = sorted(original)
print(f"\nOriginal: {original}")
print(f"Sorted copy: {sorted_list}")

# reverse() - Reverse in place
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(f"\nReversed: {numbers}")
Original: [3, 1, 4, 1, 5, 9, 2]
After sort: [1, 1, 2, 3, 4, 5, 9]
Sorted descending: [9, 5, 4, 3, 2, 1, 1]

Original: [5, 2, 8, 1]
Sorted copy: [1, 2, 5, 8]

Reversed: [5, 4, 3, 2, 1]

Checking Membership

fruits = ["apple", "banana", "cherry"]

# Check if item exists
print(f"'banana' in fruits: {'banana' in fruits}")
print(f"'grape' in fruits: {'grape' in fruits}")
print(f"'grape' not in fruits: {'grape' not in fruits}")
'banana' in fruits: True
'grape' in fruits: False
'grape' not in fruits: True

6.6 Dictionaries: Key-Value Pairs

A dictionary is an unordered collection of key-value pairs. Think of it like a real dictionary where you look up a word (key) to find its definition (value).

Creating Dictionaries

You create dictionaries using curly braces {} with key: value pairs:

# Empty dictionary
empty_dict = {}

# Dictionary with data
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

print(person)

# Another example
scores = {
    "math": 95,
    "english": 88,
    "science": 92
}

print(scores)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
{'math': 95, 'english': 88, 'science': 92}

Accessing Dictionary Values

Access values using their keys with square brackets:

person = {
    "name": "Bob",
    "age": 25,
    "city": "London",
    "job": "Engineer"
}

# Access values by key
print(f"Name: {person['name']}")
print(f"Age: {person['age']}")
print(f"City: {person['city']}")
Name: Bob
Age: 25
City: London

get() Method - Safe Access

The get() method is safer than [] because it doesn’t error if the key doesn’t exist:

person = {"name": "Charlie", "age": 35}

# Using get() - returns None if key doesn't exist
print(f"Name: {person.get('name')}")
print(f"Email: {person.get('email')}")  # Returns None

# Provide a default value
print(f"Email: {person.get('email', 'Not provided')}")
Name: Charlie
Email: None
Email: Not provided

6.7 Dictionary Operations: Adding and Modifying

Adding New Key-Value Pairs

person = {"name": "Alice", "age": 30}
print(f"Original: {person}")

# Add new key-value pair
person["city"] = "Paris"
print(f"After adding city: {person}")

person["job"] = "Designer"
print(f"After adding job: {person}")
Original: {'name': 'Alice', 'age': 30}
After adding city: {'name': 'Alice', 'age': 30, 'city': 'Paris'}
After adding job: {'name': 'Alice', 'age': 30, 'city': 'Paris', 'job': 'Designer'}

Modifying Existing Values

scores = {"math": 85, "english": 90}
print(f"Original: {scores}")

# Modify existing value
scores["math"] = 95
print(f"After update: {scores}")
Original: {'math': 85, 'english': 90}
After update: {'math': 95, 'english': 90}

update() - Merge Dictionaries

person = {"name": "Bob", "age": 25}
additional_info = {"city": "Tokyo", "job": "Teacher"}

print(f"Before update: {person}")
person.update(additional_info)
print(f"After update: {person}")
Before update: {'name': 'Bob', 'age': 25}
After update: {'name': 'Bob', 'age': 25, 'city': 'Tokyo', 'job': 'Teacher'}

6.8 Dictionary Operations: Removing Items

pop() - Remove by Key

person = {"name": "Alice", "age": 30, "city": "Berlin"}
print(f"Original: {person}")

# Remove and return value
age = person.pop("age")
print(f"Popped value: {age}")
print(f"After pop: {person}")
Original: {'name': 'Alice', 'age': 30, 'city': 'Berlin'}
Popped value: 30
After pop: {'name': 'Alice', 'city': 'Berlin'}

del - Remove by Key

student = {"name": "Charlie", "grade": "A", "age": 20}
print(f"Before del: {student}")

del student["age"]
print(f"After del: {student}")
Before del: {'name': 'Charlie', 'grade': 'A', 'age': 20}
After del: {'name': 'Charlie', 'grade': 'A'}

clear() - Remove All Items

data = {"a": 1, "b": 2, "c": 3}
print(f"Before clear: {data}")

data.clear()
print(f"After clear: {data}")
Before clear: {'a': 1, 'b': 2, 'c': 3}
After clear: {}

6.9 Dictionary Operations: Useful Methods

keys(), values(), and items()

student = {
    "name": "David",
    "age": 22,
    "major": "Computer Science",
    "gpa": 3.8
}

# Get all keys
print(f"Keys: {list(student.keys())}")

# Get all values
print(f"Values: {list(student.values())}")

# Get all key-value pairs
print(f"Items: {list(student.items())}")
Keys: ['name', 'age', 'major', 'gpa']
Values: ['David', 22, 'Computer Science', 3.8]
Items: [('name', 'David'), ('age', 22), ('major', 'Computer Science'), ('gpa', 3.8)]

Checking Membership

person = {"name": "Eve", "age": 28, "city": "Sydney"}

# Check if key exists
print(f"'name' in person: {'name' in person}")
print(f"'email' in person: {'email' in person}")
'name' in person: True
'email' in person: False

Length

scores = {"math": 90, "english": 85, "science": 92}
print(f"Number of subjects: {len(scores)}")
Number of subjects: 3

6.10 Iterating Through Data Structures

Looping Through Lists

fruits = ["apple", "banana", "cherry"]

# Method 1: Iterate over values
print("Fruits:")
for fruit in fruits:
    print(f"  - {fruit}")

# Method 2: Iterate with index
print("\nFruits with index:")
for i, fruit in enumerate(fruits):
    print(f"  {i}: {fruit}")
Fruits:
  - apple
  - banana
  - cherry

Fruits with index:
  0: apple
  1: banana
  2: cherry

Looping Through Dictionaries

person = {"name": "Frank", "age": 32, "city": "Toronto"}

# Method 1: Iterate over keys
print("Keys:")
for key in person:
    print(f"  {key}")

# Method 2: Iterate over values
print("\nValues:")
for value in person.values():
    print(f"  {value}")

# Method 3: Iterate over key-value pairs
print("\nKey-Value pairs:")
for key, value in person.items():
    print(f"  {key}: {value}")
Keys:
  name
  age
  city

Values:
  Frank
  32
  Toronto

Key-Value pairs:
  name: Frank
  age: 32
  city: Toronto

6.11 Nested Data Structures

You can combine lists and dictionaries to create more complex structures:

Lists of Dictionaries

# List of students
students = [
    {"name": "Alice", "age": 20, "grade": "A"},
    {"name": "Bob", "age": 21, "grade": "B"},
    {"name": "Charlie", "age": 19, "grade": "A"}
]

print("Students:")
for student in students:
    print(f"  {student['name']} (age {student['age']}): Grade {student['grade']}")
Students:
  Alice (age 20): Grade A
  Bob (age 21): Grade B
  Charlie (age 19): Grade A

Dictionary with List Values

# Student with multiple test scores
student = {
    "name": "Diana",
    "scores": [85, 90, 92, 88],
    "subjects": ["math", "english", "science", "history"]
}

print(f"Student: {student['name']}")
print(f"Scores: {student['scores']}")
print(f"Average: {sum(student['scores']) / len(student['scores']):.2f}")
Student: Diana
Scores: [85, 90, 92, 88]
Average: 88.75

6.12 Practice Exercises

Now it’s your turn! Try these exercises:

Exercise 1: Shopping List

Create a shopping list and perform operations on it:

# Create a shopping list with 3 items
shopping_list =

# Add 2 more items
# Remove one item
# Print the final list and its length

Exercise 2: Student Information

Create a dictionary for a student and manipulate it:

# Create a student dictionary with name, age, and major
student =

# Add a 'gpa' key
# Update the age
# Print all keys and values

Exercise 3: Grade Book

Create a grade book for multiple students:

# Create a list of at least 3 student dictionaries
# Each student should have name and grade
students =

# Print each student's information
# Calculate and print the average grade

6.13 Solutions

Here are the solutions to the exercises:

Solution 1:

Click to show solution
# Create shopping list
shopping_list = ["milk", "bread", "eggs"]
print(f"Original list: {shopping_list}")

# Add items
shopping_list.append("butter")
shopping_list.append("cheese")
print(f"After adding: {shopping_list}")

# Remove item
shopping_list.remove("bread")
print(f"After removing: {shopping_list}")
print(f"Final length: {len(shopping_list)}")
Original list: ['milk', 'bread', 'eggs']
After adding: ['milk', 'bread', 'eggs', 'butter', 'cheese']
After removing: ['milk', 'eggs', 'butter', 'cheese']
Final length: 4

Solution 2:

Click to show solution
# Create student dictionary
student = {
    "name": "Emma",
    "age": 20,
    "major": "Biology"
}
print(f"Original: {student}")

# Add GPA
student["gpa"] = 3.7
print(f"After adding GPA: {student}")

# Update age
student["age"] = 21
print(f"After updating age: {student}")

# Print keys and values
print(f"\nKeys: {list(student.keys())}")
print(f"Values: {list(student.values())}")
Original: {'name': 'Emma', 'age': 20, 'major': 'Biology'}
After adding GPA: {'name': 'Emma', 'age': 20, 'major': 'Biology', 'gpa': 3.7}
After updating age: {'name': 'Emma', 'age': 21, 'major': 'Biology', 'gpa': 3.7}

Keys: ['name', 'age', 'major', 'gpa']
Values: ['Emma', 21, 'Biology', 3.7]

Solution 3:

Click to show solution
# Create grade book
students = [
    {"name": "Alice", "grade": 92},
    {"name": "Bob", "grade": 85},
    {"name": "Charlie", "grade": 88}
]

# Print each student
print("Grade Book:")
for student in students:
    print(f"  {student['name']}: {student['grade']}")

# Calculate average
total = sum(student["grade"] for student in students)
average = total / len(students)
print(f"\nAverage grade: {average:.2f}")
Grade Book:
  Alice: 92
  Bob: 85
  Charlie: 88

Average grade: 88.33

6.14 Key Takeaways

Lists: - Ordered collections that you can modify - Access elements by index (starting at 0) - Methods: append(), insert(), remove(), pop(), sort(), reverse() - Use len() to get the length

Dictionaries: - Store key-value pairs - Access values by key - Methods: get(), keys(), values(), items(), pop(), update() - Use len() to get the number of key-value pairs

When to Use: - Use lists when you have an ordered collection of similar items - Use dictionaries when you need to associate keys with values

6.15 Next Steps

Now that you understand lists and dictionaries, you’re ready to explore: - Tuples and sets (other data structures) - List comprehensions (elegant way to create lists) - Dictionary comprehensions - Advanced data manipulation techniques

Keep practicing and building with data structures!