Data Structures
Section 3: Data Structures
Lesson 1: Lists and Tuples
1.1 Creating and Manipulating Lists
Lists in Python are versatile data structures that can hold a collection of items. They are mutable, meaning you can modify their elements.
Example:
# Creating and manipulating lists
fruits = ["apple", "banana", "orange"]
# Accessing elements
print(fruits[0]) # Output: apple
# Modifying elements
fruits[1] = "grape"
print(fruits) # Output: ['apple', 'grape', 'orange']
# Adding elements
fruits.append("kiwi")
print(fruits) # Output: ['apple', 'grape', 'orange', 'kiwi']
1.2 Working with Tuples
Tuples are similar to lists but are immutable, meaning their elements cannot be changed once set.
Example:
# Working with tuples
coordinates = (3, 4)
# Accessing elements
x, y = coordinates
print("X:", x) # Output: 3
print("Y:", y) # Output: 4
Lesson 2: Dictionaries and Sets
2.1 Understanding Dictionaries
Dictionaries are unordered collections of items, where each item consists of a key-value pair.
Example:
# Understanding dictionaries
student = {
"name": "Alice",
"age": 22,
"major": "Computer Science"
}
# Accessing values
print(student["name"]) # Output: Alice
# Modifying values
student["age"] = 23
print(student) # Output: {'name': 'Alice', 'age': 23, 'major': 'Computer Science'}
# Adding new key-value pairs
student["grade"] = "A"
print(student) # Output: {'name': 'Alice', 'age': 23, 'major': 'Computer Science', 'grade': 'A'}
2.2 Operations on Sets
Sets are unordered collections of unique elements. They support various operations like union, intersection, and difference.
Example:
# Operations on sets
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# Union
union_set = set_a.union(set_b)
print(union_set) # Output: {1, 2, 3, 4, 5, 6}
# Intersection
intersection_set = set_a.intersection(set_b)
print(intersection_set) # Output: {3, 4}
# Difference
difference_set = set_a - set_b
print(difference_set) # Output: {1, 2}
In Section 3, we explored essential data structures in Python: lists, tuples, dictionaries, and sets. Lists and tuples provide ways to organize and manipulate collections of items, with lists being mutable and tuples being immutable.
Dictionaries offer a key-value mapping for efficient data retrieval and modification. Sets, with their unique and unordered nature, enable operations like union, intersection, and difference.
Understanding these data structures and their respective use cases is fundamental for effective Python programming. As you incorporate lists, tuples, dictionaries, and sets into your code, you enhance your ability to organize, access, and manipulate data efficiently. These data structures play a central role in building versatile and powerful Python applications.