Introduction
Data structures are essential for organizing and storing data efficiently. Python provides several built-in data structures, including lists, tuples, sets, and dictionaries. This step will guide you through these fundamental structures and how to use them effectively.
1. Lists (Dynamic Arrays)
Lists are ordered, mutable collections of elements.
Creating a List
fruits = ["apple", "banana", "cherry"]
print(fruits)
Accessing Elements
print(fruits[0]) # First element
print(fruits[-1]) # Last element
Modifying a List
fruits.append("orange") # Add an element
fruits.remove("banana") # Remove an element
fruits[0] = "grape" # Modify an element
print(fruits)
List Slicing
print(fruits[1:3]) # Get elements from index 1 to 2
2. Tuples (Immutable Collections)
Tuples are similar to lists but immutable (cannot be changed after creation).
Creating a Tuple
tuple_example = (1, 2, 3, "hello")
print(tuple_example)
Accessing Elements
print(tuple_example[1])
Tuple Unpacking
a, b, c, d = tuple_example
print(a, d)
3. Sets (Unordered, Unique Elements)
Sets store unique, unordered elements.
Creating a Set
numbers = {1, 2, 3, 4, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5} (no duplicates)
Adding & Removing Elements
numbers.add(6)
numbers.remove(3)
print(numbers)
Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
4. Dictionaries (Key-Value Pairs)
Dictionaries store data as key-value pairs.
Creating a Dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)
Accessing Values
print(person["name"])
Modifying a Dictionary
person["age"] = 30 # Update value
person["country"] = "USA" # Add new key-value pair
print(person)
Removing Elements
del person["city"]
print(person)
5. Choosing the Right Data Structure
- Use lists when the order of elements matters.
- Use tuples when you need an immutable sequence.
- Use sets for unique elements and fast membership testing.
- Use dictionaries when data is best represented as key-value pairs.
Exercises
- Create a list of your favorite movies and perform basic operations (add, remove, slice).
- Create a tuple containing three numbers and unpack its values.
- Create a set and perform union and intersection operations with another set.
- Create a dictionary representing a book (title, author, year) and modify it.
Conclusion
You now understand Python's built-in data structures and how to manipulate them effectively. The next step is to learn about control flow with loops and conditionals.