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 listempty_list = []# List of numbersnumbers = [1, 2, 3, 4, 5]# List of stringsfruits = ["apple", "banana", "cherry"]# List with mixed typesmixed = [1, "hello", 3.14, True]print(numbers)print(fruits)print(mixed)
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 elementsprint(f"numbers[:3]: {numbers[:3]}")# Get elements from index 5 to endprint(f"numbers[5:]: {numbers[5:]}")# Get every second elementprint(f"numbers[::2]: {numbers[::2]}")# Reverse a listprint(f"numbers[::-1]: {numbers[::-1]}")
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 elementlast = numbers.pop()print(f"Popped: {last}")print(f"After pop: {numbers}")# Remove and return element at index 1second = 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]
numbers = [1, 2, 3, 2, 4, 2, 5]# Get lengthprint(f"Length: {len(numbers)}")# Count occurrencesprint(f"Count of 2: {numbers.count(2)}")# Find index of first occurrenceprint(f"Index of 3: {numbers.index(3)}")
fruits = ["apple", "banana", "cherry"]# Check if item existsprint(f"'banana' in fruits: {'banana'in fruits}")print(f"'grape' in fruits: {'grape'in fruits}")print(f"'grape' not in fruits: {'grape'notin 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 dictionaryempty_dict = {}# Dictionary with dataperson = {"name": "Alice","age": 30,"city": "New York"}print(person)# Another examplescores = {"math": 95,"english": 88,"science": 92}print(scores)
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 keysprint(f"Keys: {list(student.keys())}")# Get all valuesprint(f"Values: {list(student.values())}")# Get all key-value pairsprint(f"Items: {list(student.items())}")
person = {"name": "Eve", "age": 28, "city": "Sydney"}# Check if key existsprint(f"'name' in person: {'name'in person}")print(f"'email' in person: {'email'in person}")
fruits = ["apple", "banana", "cherry"]# Method 1: Iterate over valuesprint("Fruits:")for fruit in fruits:print(f" - {fruit}")# Method 2: Iterate with indexprint("\nFruits with index:")for i, fruit inenumerate(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 keysprint("Keys:")for key in person:print(f" {key}")# Method 2: Iterate over valuesprint("\nValues:")for value in person.values():print(f" {value}")# Method 3: Iterate over key-value pairsprint("\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:
Create a shopping list and perform operations on it:
# Create a shopping list with 3 itemsshopping_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 majorstudent =# 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 gradestudents =# Print each student's information# Calculate and print the average grade
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!
---title: "Data Structures"jupyter: python3---## Organizing Multiple Pieces of DataIn 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## Lists: Ordered CollectionsA 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 {.unnumbered}You create lists using square brackets `[]` with items separated by commas:```{python}# Empty listempty_list = []# List of numbersnumbers = [1, 2, 3, 4, 5]# List of stringsfruits = ["apple", "banana", "cherry"]# List with mixed typesmixed = [1, "hello", 3.14, True]print(numbers)print(fruits)print(mixed)```### Accessing List Elements {.unnumbered}Lists are **indexed** starting from 0. You access elements using square brackets:```{python}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]}")```### List Slicing {.unnumbered}You can extract portions of a list using slicing `[start:end]`:```{python}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 elementsprint(f"numbers[:3]: {numbers[:3]}")# Get elements from index 5 to endprint(f"numbers[5:]: {numbers[5:]}")# Get every second elementprint(f"numbers[::2]: {numbers[::2]}")# Reverse a listprint(f"numbers[::-1]: {numbers[::-1]}")```## List Operations: Adding ElementsLists are **mutable**, meaning you can change them after creation. Here are ways to add elements:### append() - Add to End {.unnumbered}```{python}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}")```### insert() - Add at Specific Position {.unnumbered}```{python}colors = ["red", "blue", "green"]print(f"Original: {colors}")# Insert "yellow" at index 1colors.insert(1, "yellow")print(f"After insert: {colors}")```### extend() - Add Multiple Elements {.unnumbered}```{python}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 + operatorlist3 = [7, 8, 9]combined = list1 + list3print(f"Combined list: {combined}")```## List Operations: Removing Elements### remove() - Remove by Value {.unnumbered}```{python}fruits = ["apple", "banana", "cherry", "banana"]print(f"Original: {fruits}")# Remove first occurrence of "banana"fruits.remove("banana")print(f"After remove: {fruits}")```### pop() - Remove by Index {.unnumbered}```{python}numbers = [10, 20, 30, 40, 50]print(f"Original: {numbers}")# Remove and return last elementlast = numbers.pop()print(f"Popped: {last}")print(f"After pop: {numbers}")# Remove and return element at index 1second = numbers.pop(1)print(f"Popped at index 1: {second}")print(f"After pop(1): {numbers}")```### clear() - Remove All Elements {.unnumbered}```{python}items = [1, 2, 3, 4, 5]print(f"Before clear: {items}")items.clear()print(f"After clear: {items}")```## List Operations: Other Useful Methods### Length, Count, and Index {.unnumbered}```{python}numbers = [1, 2, 3, 2, 4, 2, 5]# Get lengthprint(f"Length: {len(numbers)}")# Count occurrencesprint(f"Count of 2: {numbers.count(2)}")# Find index of first occurrenceprint(f"Index of 3: {numbers.index(3)}")```### Sorting and Reversing {.unnumbered}```{python}# sort() - Sort in placenumbers = [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 listoriginal = [5, 2, 8, 1]sorted_list =sorted(original)print(f"\nOriginal: {original}")print(f"Sorted copy: {sorted_list}")# reverse() - Reverse in placenumbers = [1, 2, 3, 4, 5]numbers.reverse()print(f"\nReversed: {numbers}")```### Checking Membership {.unnumbered}```{python}fruits = ["apple", "banana", "cherry"]# Check if item existsprint(f"'banana' in fruits: {'banana'in fruits}")print(f"'grape' in fruits: {'grape'in fruits}")print(f"'grape' not in fruits: {'grape'notin fruits}")```## Dictionaries: Key-Value PairsA 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 {.unnumbered}You create dictionaries using curly braces `{}` with `key: value` pairs:```{python}# Empty dictionaryempty_dict = {}# Dictionary with dataperson = {"name": "Alice","age": 30,"city": "New York"}print(person)# Another examplescores = {"math": 95,"english": 88,"science": 92}print(scores)```### Accessing Dictionary Values {.unnumbered}Access values using their keys with square brackets:```{python}person = {"name": "Bob","age": 25,"city": "London","job": "Engineer"}# Access values by keyprint(f"Name: {person['name']}")print(f"Age: {person['age']}")print(f"City: {person['city']}")```### get() Method - Safe Access {.unnumbered}The `get()` method is safer than `[]` because it doesn't error if the key doesn't exist:```{python}person = {"name": "Charlie", "age": 35}# Using get() - returns None if key doesn't existprint(f"Name: {person.get('name')}")print(f"Email: {person.get('email')}") # Returns None# Provide a default valueprint(f"Email: {person.get('email', 'Not provided')}")```## Dictionary Operations: Adding and Modifying### Adding New Key-Value Pairs {.unnumbered}```{python}person = {"name": "Alice", "age": 30}print(f"Original: {person}")# Add new key-value pairperson["city"] ="Paris"print(f"After adding city: {person}")person["job"] ="Designer"print(f"After adding job: {person}")```### Modifying Existing Values {.unnumbered}```{python}scores = {"math": 85, "english": 90}print(f"Original: {scores}")# Modify existing valuescores["math"] =95print(f"After update: {scores}")```### update() - Merge Dictionaries {.unnumbered}```{python}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}")```## Dictionary Operations: Removing Items### pop() - Remove by Key {.unnumbered}```{python}person = {"name": "Alice", "age": 30, "city": "Berlin"}print(f"Original: {person}")# Remove and return valueage = person.pop("age")print(f"Popped value: {age}")print(f"After pop: {person}")```### del - Remove by Key {.unnumbered}```{python}student = {"name": "Charlie", "grade": "A", "age": 20}print(f"Before del: {student}")del student["age"]print(f"After del: {student}")```### clear() - Remove All Items {.unnumbered}```{python}data = {"a": 1, "b": 2, "c": 3}print(f"Before clear: {data}")data.clear()print(f"After clear: {data}")```## Dictionary Operations: Useful Methods### keys(), values(), and items() {.unnumbered}```{python}student = {"name": "David","age": 22,"major": "Computer Science","gpa": 3.8}# Get all keysprint(f"Keys: {list(student.keys())}")# Get all valuesprint(f"Values: {list(student.values())}")# Get all key-value pairsprint(f"Items: {list(student.items())}")```### Checking Membership {.unnumbered}```{python}person = {"name": "Eve", "age": 28, "city": "Sydney"}# Check if key existsprint(f"'name' in person: {'name'in person}")print(f"'email' in person: {'email'in person}")```### Length {.unnumbered}```{python}scores = {"math": 90, "english": 85, "science": 92}print(f"Number of subjects: {len(scores)}")```## Iterating Through Data Structures### Looping Through Lists {.unnumbered}```{python}fruits = ["apple", "banana", "cherry"]# Method 1: Iterate over valuesprint("Fruits:")for fruit in fruits:print(f" - {fruit}")# Method 2: Iterate with indexprint("\nFruits with index:")for i, fruit inenumerate(fruits):print(f" {i}: {fruit}")```### Looping Through Dictionaries {.unnumbered}```{python}person = {"name": "Frank", "age": 32, "city": "Toronto"}# Method 1: Iterate over keysprint("Keys:")for key in person:print(f" {key}")# Method 2: Iterate over valuesprint("\nValues:")for value in person.values():print(f" {value}")# Method 3: Iterate over key-value pairsprint("\nKey-Value pairs:")for key, value in person.items():print(f" {key}: {value}")```## Nested Data StructuresYou can combine lists and dictionaries to create more complex structures:### Lists of Dictionaries {.unnumbered}```{python}# List of studentsstudents = [ {"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']}")```### Dictionary with List Values {.unnumbered}```{python}# Student with multiple test scoresstudent = {"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}")```## Practice ExercisesNow it's your turn! Try these exercises:### Exercise 1: Shopping List {.unnumbered}Create a shopping list and perform operations on it:```{python}#| eval: false# Create a shopping list with 3 itemsshopping_list =# Add 2 more items# Remove one item# Print the final list and its length```### Exercise 2: Student Information {.unnumbered}Create a dictionary for a student and manipulate it:```{python}#| eval: false# Create a student dictionary with name, age, and majorstudent =# Add a 'gpa' key# Update the age# Print all keys and values```### Exercise 3: Grade Book {.unnumbered}Create a grade book for multiple students:```{python}#| eval: false# Create a list of at least 3 student dictionaries# Each student should have name and gradestudents =# Print each student's information# Calculate and print the average grade```## SolutionsHere are the solutions to the exercises:### Solution 1: {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"# Create shopping listshopping_list = ["milk", "bread", "eggs"]print(f"Original list: {shopping_list}")# Add itemsshopping_list.append("butter")shopping_list.append("cheese")print(f"After adding: {shopping_list}")# Remove itemshopping_list.remove("bread")print(f"After removing: {shopping_list}")print(f"Final length: {len(shopping_list)}")```### Solution 2: {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"# Create student dictionarystudent = {"name": "Emma","age": 20,"major": "Biology"}print(f"Original: {student}")# Add GPAstudent["gpa"] =3.7print(f"After adding GPA: {student}")# Update agestudent["age"] =21print(f"After updating age: {student}")# Print keys and valuesprint(f"\nKeys: {list(student.keys())}")print(f"Values: {list(student.values())}")```### Solution 3: {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"# Create grade bookstudents = [ {"name": "Alice", "grade": 92}, {"name": "Bob", "grade": 85}, {"name": "Charlie", "grade": 88}]# Print each studentprint("Grade Book:")for student in students:print(f" {student['name']}: {student['grade']}")# Calculate averagetotal =sum(student["grade"] for student in students)average = total /len(students)print(f"\nAverage grade: {average:.2f}")```## 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## Next StepsNow 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 techniquesKeep practicing and building with data structures!