Data Structures in Python

Python offers a variety of built-in data structures that are both powerful and easy to use. They are crucial for organizing, managing, and storing data in a structured way. Here’s how you can explain each of these data structures to students:

Lists

A list is a mutable, ordered sequence of items that can contain elements of different types.

Creating Lists

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

Accessing Elements: Elements in a list can be accessed by their index, starting from zero.

Accessing Elements

# Accessing list elements
first_fruit = fruits[0]  # Outputs: apple
                

List Operations and Methods: Lists can be modified post-creation. Python provides many list methods such as append(), remove(), pop(), reverse(), and more.

List Operations and Methods

# Adding an element
fruits.append("date")

# Removing an element
fruits.remove("banana")
                

List Comprehensions: They provide a concise way to create lists. Common applications include making new lists where each element is the result of some operation.

List Comprehensions

# List comprehension
squares = [x**2 for x in range(10)]
                

Tuples

A tuple is an immutable, ordered sequence of elements.

Creating Tuples

# Creating a tuple
dimensions = (20, 50)
                

Immutable Nature: Once a tuple is created, you cannot change its values. Tuples are useful for data that should not be modified.

Tuple Unpacking

# Tuple unpacking
width, height = dimensions
                

Sets

A set is an unordered collection of unique items.

Creating Sets

# Creating a set
unique_numbers = {1, 2, 3, 4, 5}
                

Set Operations: Sets support mathematical operations like union, intersection, difference, and symmetric difference.

Set Operations

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}

# Union
c = a | b  # Outputs: {1, 2, 3, 4, 5}

# Intersection
d = a & b  # Outputs: {3}
                

Dictionaries

A dictionary is a mutable, unordered collection of key-value pairs.

Creating Dictionaries

# Creating a dictionary
student_grades = {"Alice": 90, "Bob": 85, "Eve": 92}
                

Accessing Values: Values in a dictionary are accessed by using their keys inside square brackets [].

Accessing Values

# Accessing dictionary values
alice_grade = student_grades["Alice"]  # Outputs: 90
                

Dictionary Methods: Dictionaries have a variety of useful methods, such as get(), keys(), values(), and items().

Dictionary Methods

# Using dictionary methods
all_grades = student_grades.values()  # Outputs: dict_values([90, 85, 92])