PythonForAI Day 4: Data Structures

Welcome to Day 4 of PythonForAI! Today, we will explore three fundamental data structures in Python: lists, tuples, and dictionaries. These data structures are essential for storing and managing collections of data. We will also solve some practical problems to reinforce these concepts. Let’s get started!

Topics to Cover

1. Lists

A list is a mutable, ordered collection of items. Lists are defined by enclosing items in square brackets [].

Example

# Creating a list
fruits = ["apple", "banana", "cherry"]
print(fruits)  # Output: ['apple', 'banana', 'cherry']

# Accessing list elements
print(fruits[0])  # Output: apple
print(fruits[-1])  # Output: cherry

# Modifying list elements
fruits[1] = "blueberry"
print(fruits)  # Output: ['apple', 'blueberry', 'cherry']

# Adding elements to a list
fruits.append("date")
print(fruits)  # Output: ['apple', 'blueberry', 'cherry', 'date']

# Removing elements from a list
fruits.remove("blueberry")
print(fruits)  # Output: ['apple', 'cherry', 'date']

2. Tuples

A tuple is an immutable, ordered collection of items. Tuples are defined by enclosing items in parentheses ().

Example

# Creating a tuple
coordinates = (10, 20)
print(coordinates)  # Output: (10, 20)

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

# Tuples are immutable, so we can't modify them
# coordinates[0] = 15  # This will raise a TypeError

3. Dictionaries

A dictionary is a mutable, unordered collection of key-value pairs. Dictionaries are defined by enclosing key-value pairs in curly braces {}.

Example

# Creating a dictionary
student_grades = {"Alice": 90, "Bob": 85, "Charlie": 92}
print(student_grades)  # Output: {'Alice': 90, 'Bob': 85, 'Charlie': 92}

# Accessing dictionary elements
print(student_grades["Alice"])  # Output: 90

# Modifying dictionary elements
student_grades["Bob"] = 88
print(student_grades)  # Output: {'Alice': 90, 'Bob': 88, 'Charlie': 92}

# Adding elements to a dictionary
student_grades["David"] = 95
print(student_grades)  # Output: {'Alice': 90, 'Bob': 88, 'Charlie': 92, 'David': 95}

# Removing elements from a dictionary
del student_grades["Charlie"]
print(student_grades)  # Output: {'Alice': 90, 'Bob': 88, 'David': 95}

Potential Problems to Solve

1. Write a Program to Find the Largest Number in a List

We will write a function that takes a list of numbers as input and returns the largest number in the list.

Solution

def find_largest_number(numbers):
    if not numbers:
        return None
    largest = numbers[0]
    for number in numbers:
        if number > largest:
            largest = number
    return largest

# Test the function
numbers = [10, 20, 30, 40, 50]
print("The largest number is:", find_largest_number(numbers))  # Output: The largest number is: 50

2. Create a Dictionary to Store Student Names and Their Grades, and Write Functions to Add, Remove, and Look Up Students

We will create a dictionary to store student names and their grades. Then, we will write functions to add a student, remove a student, and look up a student’s grade.

Solution

# Creating the dictionary
student_grades = {}

# Function to add a student
def add_student(name, grade):
    student_grades[name] = grade
    print(f"Added {name} with grade {grade}")

# Function to remove a student
def remove_student(name):
    if name in student_grades:
        del student_grades[name]
        print(f"Removed {name}")
    else:
        print(f"Student {name} not found")

# Function to look up a student's grade
def look_up_grade(name):
    if name in student_grades:
        return f"{name}'s grade is {student_grades[name]}"
    else:
        return f"Student {name} not found"

# Test the functions
add_student("Alice", 90)
add_student("Bob", 85)
add_student("Charlie", 92)

print(look_up_grade("Alice"))  # Output: Alice's grade is 90
print(look_up_grade("David"))  # Output: Student David not found

remove_student("Bob")
print(student_grades)  # Output: {'Alice': 90, 'Charlie': 92}

Summary

Today, we covered three essential data structures in Python: lists, tuples, and dictionaries. These data structures are crucial for storing and managing collections of data. We also applied these concepts by solving two practical problems: finding the largest number in a list and managing student grades with a dictionary.

Data structures are foundational to programming, and mastering them will help you write more efficient and organized code. Tomorrow, we will delve into string manipulation and file I/O.

Keep practicing and experimenting with data structures to strengthen your understanding. Feel free to leave any questions or comments below, and happy coding! 🐍🚀


Additional Resources

Frequently Asked Questions (FAQs)

Q1: What are the differences between lists and tuples in Python?

  • Lists are mutable, meaning their elements can be changed. They are defined using square brackets [].
  • Tuples are immutable, meaning their elements cannot be changed. They are defined using parentheses ().

Q2: Can dictionary keys be of any data type?
Dictionary keys must be of an immutable data type, such as strings, numbers, or tuples. Lists cannot be used as dictionary keys because they are mutable.

Q3: How can I iterate over the elements of a list or tuple?
You can use a for loop to iterate over the elements of a list or tuple.

Q4: How do I check if a key exists in a dictionary?
You can use the in keyword to check if a key exists in a dictionary. For example, if key in dictionary:.

Q5: Can I nest data structures in Python?
Yes, you can nest data structures in Python. For example, you can have a list of dictionaries, a dictionary of lists, a tuple of lists, etc.

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 478