Python Data Structures_ A Comprehensive Guide
Python Data Structures_ A Comprehensive Guide
Python offers several built-in data structures, each designed for specific use cases.
Understanding their characteristics helps you write more efficient and maintainable code.
```python
# Creating and modifying lists
inventory = ["apples", 42, True]
inventory.append("oranges") # Add to end
inventory[1] = 50 # Modify element
last_item = inventory.pop() # Remove and return last item
```
**Common Operations:**
- `len()` - Get length
- Slicing - `inventory[1:3]`
- Sorting - `sorted()` or `.sort()`
- List comprehensions - `[x*2 for x in range(5)]`
**Use Cases:**
- When you need an ordered collection that changes frequently
- As stacks (`append()`/`pop()`) or queues (with `collections.deque`)
```python
# Tuple creation and usage
dimensions = (1920, 1080)
coordinates = ( (1,2), (3,4) ) # Nested tuples
# Special case: single-element tuple
singleton = (42,) # Note the comma
```
**Key Advantages:**
- Safer for constant data
- Faster iteration than lists
- Clean syntax for multiple returns: `return name, age, score`
**Use Cases:**
- Fixed data like coordinates, RGB values
- Dictionary keys (when containing immutable values)
- Multiple return values from functions
```python
# Dictionary operations
user = {
"name": "Alex",
"posts": 42,
"active": True
}
# Accessing values
name = user["name"] # Direct access
email = user.get("email", "") # Safe access with default
# Modifying
user["posts"] += 1 # Update value
user["email"] = "[email protected]" # Add new key
del user["active"] # Remove key
```
**Advanced Features:**
- Dictionary comprehensions - `{x: x**2 for x in range(5)}`
- Views: `.keys()`, `.values()`, `.items()`
- Merging: `dict1 | dict2` (Python 3.9+)
**Use Cases:**
- JSON-like data structures
- Counting occurrences (frequency tables)
- Caching/memoization
- Object representations
```python
# Set operations
primes = {2, 3, 5, 7}
primes.add(11) # Add element
primes.discard(2) # Remove safely
# Set operations
evens = {2, 4, 6, 8}
print(primes | evens) # Union
print(primes & evens) # Intersection
```
**Frozen Sets**:
Immutable version: `frozenset([1,2,3])`
**Use Cases:**
- Removing duplicates from lists
- Membership testing (faster than lists)
- Mathematical set operations
```python
from array import array
temps = array('f', [22.5, 18.0, 30.2]) # 'f' for float
temps.append(25.3)
```
**When to Use:**
- Large numeric datasets
- Interfacing with C code
- Memory-sensitive applications
```python
# String operations
message = "Hello, World!"
print(message[7:12]) # Slicing
words = message.split() # Split into list
```
**Use Cases:**
- All text processing
- Regular expression operations
- String formatting and templating