Introduction to Data Structures in Python
Data structures are essential for organizing, managing, and storing data efficiently. Python provides several built-in data structures that are easy to use and highly versatile. This guide will cover:
- Lists
- Tuples
- Sets
- Dictionaries
- Advanced Data Structures (Optional)
Data Structures in Python - Lists
A list is an ordered, mutable collection of items. It can hold items of different data types.
Creating a List:
fruits = ["apple", "banana", "cherry"]
print(fruits)
Key Operations:
Operation | Example | Output |
---|---|---|
Access an item | fruits[1] | "banana" |
Add an item | fruits.append("orange") | ["apple", "banana", "cherry", "orange"] |
Remove an item | fruits.remove("banana") | ["apple", "cherry"] |
Length of list | len(fruits) | 3 |
Sort the list | fruits.sort() | ["apple", "banana", "cherry"] |
Example:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry', 'orange']
Data Structures in Python -Tuples
A tuple is an ordered, immutable collection of items.
Creating a Tuple:
coordinates = (10, 20, 30)
print(coordinates)
Key Operations:
Operation | Example | Output |
---|---|---|
Access an item | coordinates[1] | 20 |
Length of tuple | len(coordinates) | 3 |
Tuple unpacking | x, y, z = coordinates | x=10, y=20, z=30 |
Example:
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z) # Output: 10 20 30
Data Structures in Python-Sets
A set is an unordered collection of unique items.
Creating a Set:
unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers) # Output: {1, 2, 3, 4}
Key Operations:
Operation | Example | Output |
---|---|---|
Add an item | unique_numbers.add(5) | {1, 2, 3, 4, 5} |
Remove an item | unique_numbers.remove(3) | {1, 2, 4} |
Check membership | 2 in unique_numbers | True |
Union | set1.union(set2) | Combined sets |
Intersection | set1.intersection(set2) | Common items |
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
Data Structures in Python-Dictionaries
A dictionary is an unordered collection of key-value pairs.
Creating a Dictionary:
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)
Key Operations:
Operation | Example | Output |
---|---|---|
Access a value | person["name"] | "Alice" |
Add a key-value pair | person["job"] = "Developer" | Adds job key |
Remove a key-value | del person["age"] | Removes age |
Get keys | person.keys() | ["name", "city", "job"] |
Get values | person.values() | ["Alice", "New York", "Developer"] |
Example:
person = {"name": "Alice", "age": 25}
person["city"] = "New York"
del person["age"]
print(person) # Output: {'name': 'Alice', 'city': 'New York'}
Advanced Data Structures
Nested Lists and Dictionaries:
Nested List Example:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # Output: 6
Nested Dictionary Example:
employees = {
"emp1": {"name": "Alice", "age": 25},
"emp2": {"name": "Bob", "age": 30}
}
print(employees["emp1"]["name"]) # Output: Alice
Best Practices for Using Data Structures
Choose the Right Data Structure:
- Use lists for ordered collections.
- Use tuples for immutable data.
- Use sets for unique items.
- Use dictionaries for key-value mappings.
Avoid Nested Structures When Possible:
- Keep data structures simple to enhance readability.
Use List Comprehensions:
- Example:
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Handle Missing Keys in Dictionaries:
- Use
.get()
to handle missing keys:
print(person.get("job", "Not Found")) # Output: Not Found
Use Built-in Methods:
- Take advantage of Python’s powerful built-in methods like
sort()
,keys()
, andintersection()
.