Data structures are the backbone of efficient programming. They are ways of organizing and storing data so operations like insertion, deletion, search, and access can be performed efficiently. Python comes with several built-in data structures that are simple to use yet powerful in application.
In this chapter, we will explore the four main built-in data structures in Python: lists, tuples, sets, and dictionaries. We’ll also cover advanced structures like nested collections, stacks, queues, and an introduction to custom data structures using classes. Practical examples and best practices will help you master their real-world applications.
Table of Contents
1. Introduction to Data Structures
A data structure defines a way to organize, manage, and store data for efficient access and modification.
Why are data structures important?
- Help reduce time and space complexity
- Essential for solving complex problems
- Enable efficient data storage and retrieval
- Foundation of algorithms
2. Lists
Lists are ordered, mutable collections that can hold heterogeneous elements.
Syntax:
fruits = ["apple", "banana", "cherry"]
Common Operations:
fruits.append("mango") # Add to end
fruits.insert(1, "orange") # Insert at position
fruits.remove("banana") # Remove by value
last = fruits.pop() # Remove last item
fruits.sort() # Sort list
Accessing Elements:
fruits[0] # First item
fruits[-1] # Last item
fruits[1:3] # Slice from index 1 to 2
Nested Lists:
matrix = [[1, 2], [3, 4]]
print(matrix[1][0]) # Output: 3
3. Tuples
Tuples are ordered, immutable sequences. Once created, values cannot be changed.
Syntax:
point = (4, 5)
Use Cases:
- Fixed data
- As dictionary keys
- Return multiple values from a function
Tuple Packing and Unpacking:
a, b = (1, 2)
4. Sets
Sets are unordered, mutable collections with no duplicate elements.
Syntax:
colors = {"red", "green", "blue"}
Key Operations:
colors.add("yellow")
colors.remove("green")
Set Operations:
a = {1, 2, 3}
b = {3, 4, 5}
a | b # Union
a & b # Intersection
a - b # Difference
a ^ b # Symmetric difference
Use Cases:
- Removing duplicates from a list
- Membership testing
- Set algebra
5. Dictionaries
Dictionaries are unordered collections of key-value pairs.
Syntax:
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
Operations:
person["age"] = 31 # Update value
person["job"] = "Engineer" # Add new key-value
person.pop("city") # Remove by key
Methods:
person.keys()
person.values()
person.items()
Nested Dictionaries:
students = {
"001": {"name": "Bob", "score": 85},
"002": {"name": "Sara", "score": 90}
}
6. Nested Data Structures
You can combine multiple data structures:
classroom = [
{"name": "Alex", "grades": [80, 85]},
{"name": "Rita", "grades": [90, 92]}
]
Accessing nested values:
print(classroom[0]["grades"][1]) # Output: 85
7. Looping Through Data Structures
Lists:
for fruit in fruits:
print(fruit)
Dictionaries:
for key, value in person.items():
print(key, value)
Sets:
for color in colors:
print(color)
8. Membership and Length
"apple" in fruits
len(person)
9. Shallow vs Deep Copy
Shallow Copy:
import copy
original = [1, 2, [3, 4]]
shallow = copy.copy(original)
Deep Copy:
deep = copy.deepcopy(original)
10. Stack and Queue Implementation
Python doesn’t have built-in stacks/queues, but lists and collections.deque
can be used.
Stack (LIFO):
stack = []
stack.append(10)
stack.pop()
Queue (FIFO):
from collections import deque
queue = deque()
queue.append(1)
queue.popleft()
11. Comprehensions
List Comprehension:
squares = [x**2 for x in range(10)]
Dictionary Comprehension:
square_dict = {x: x**2 for x in range(5)}
Set Comprehension:
unique = {x for x in "hello"}
12. Common Mistakes
- Using mutable types as dictionary keys
- Modifying lists during iteration
- Confusing shallow and deep copy
- Forgetting that sets are unordered
Tips:
- Use
get()
for safe dictionary access - Avoid modifying a list while looping over it
- Use comprehensions for concise code
13. Best Practices
- Choose the right data structure for the task
- Use
defaultdict
orCounter
fromcollections
for counting - Use comprehensions for readability
- Avoid unnecessary nesting
14. Real-World Use Cases
- Lists: Shopping carts, logs, student marks
- Tuples: Coordinates, fixed config data
- Sets: Deduplication, fast membership test
- Dictionaries: JSON parsing, caching, object storage
15. Exercises
- Write a program to find unique items in a list using a set.
- Create a nested dictionary for storing employee records.
- Write a function to reverse a list without using built-in methods.
- Use a queue to simulate a call center.
- Use list comprehension to create a list of even numbers.
- Count character frequencies in a string using a dictionary.
16. Summary
Python offers rich, built-in data structures that simplify development and provide powerful tools for managing data. Mastering lists, tuples, sets, and dictionaries — along with techniques like comprehensions, stacking, queuing, and nesting — empowers you to write clean, efficient, and scalable Python code.
✅ Next Chapter: File Handling – Learn how to read, write, and process files using Python’s built-in I/O capabilities.