Data structures are used to organize and store data efficiently. Python provides several built-in data structures that allow for different kinds of operations and use cases.
1. Lists
A list is an ordered, mutable collection of items. Lists can store elements of different data types.
Key Features:
- Ordered (maintains the sequence of elements).
- Allows duplicates.
- Mutable (can be modified after creation).
Examples:
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(fruits[0]) # Output: apple
# Modifying elements
fruits[1] = "blueberry"
# Adding elements
fruits.append("orange")
# Removing elements
fruits.remove("cherry")
# Iterating through a list
for fruit in fruits:
print(fruit)
2. Tuples
A tuple is an ordered, immutable collection of items. It is similar to a list but cannot be modified after creation.
Key Features:
- Ordered.
- Immutable (cannot be changed after creation).
- Allows duplicates.
Examples:
# Creating a tuple
coordinates = (10, 20, 30)
# Accessing elements
print(coordinates[1]) # Output: 20
# Iterating through a tuple
for value in coordinates:
print(value)
3. Dictionaries
A dictionary is an unordered collection of key-value pairs. Keys must be unique and immutable, while values can be of any data type.
Key Features:
- Unordered (Python 3.7+ maintains insertion order).
- Keys are unique.
- Mutable (can add, modify, or delete items).
Examples:
# Creating a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
# Accessing values
print(person["name"]) # Output: Alice
# Modifying values
person["age"] = 26
# Adding a key-value pair
person["job"] = "Engineer"
# Removing a key-value pair
del person["city"]
# Iterating through a dictionary
for key, value in person.items():
print(f"{key}: {value}")
4. Sets
A set is an unordered collection of unique items. It is useful for removing duplicates and performing mathematical operations like union, intersection, and difference.
Key Features:
- Unordered.
- No duplicate elements.
- Mutable (can add or remove items).
Examples:
# Creating a set
numbers = {1, 2, 3, 4}
# Adding elements
numbers.add(5)
# Removing elements
numbers.remove(3)
# Checking membership
print(2 in numbers) # Output: True
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
5. Strings (as a Data Structure)
Strings are immutable sequences of characters. While not traditionally thought of as a data structure, strings support many operations similar to lists.
Examples:
text = "hello"
# Accessing characters
print(text[1]) # Output: e
# Slicing
print(text[1:4]) # Output: ell
# Iterating through a string
for char in text:
print(char)
6. Advanced Data Structures
Python also provides libraries like collections
and numpy
for advanced data structures.
- Deque (from
collections
): Double-ended queue for fast appends and pops.pythonCopy codefrom collections import deque dq = deque([1, 2, 3]) dq.append(4) dq.appendleft(0) print(dq) # Output: deque([0, 1, 2, 3, 4])
- Arrays (from
numpy
): Efficient handling of numerical data.pythonCopy codeimport numpy as np arr = np.array([1, 2, 3, 4]) print(arr + 1) # Output: [2 3 4 5]
Comparison of Data Structures
Feature | List | Tuple | Dictionary | Set |
---|---|---|---|---|
Ordered | ✅ | ✅ | ❌ (3.7+: ✅) | ❌ |
Mutable | ✅ | ❌ | ✅ | ✅ |
Allows Duplicates | ✅ | ✅ | Keys: ❌, Values: ✅ | ❌ |
Access by Index | ✅ | ✅ | ❌ | ❌ |
Understanding these data structures and their properties helps you choose the right one for your program’s needs.
One response
very helpful concepts