Data Structures in Python
It seems there might be a typo, and you meant **"Data Structures in Python"**. Below is a detailed explanation of Python's core data structures, including examples and use cases.
---
### **1. List**
- **Description**: Ordered, mutable (changeable), allows duplicates.
- **Use Case**: Storing collections of items (e.g., numbers, strings).
- **Example**:
```python
my_list = [1, 2, 3, "apple"]
my_list.append(4) # Add to end: [1, 2, 3, 'apple', 4]
my_list.pop(0) # Remove first element: [2, 3, 'apple', 4]
```
### **2. Tuple**
- **Description**: Ordered, **immutable** (unchangeable), allows duplicates.
- **Use Case**: Storing fixed data (e.g., coordinates, database records).
- **Example**:
```python
my_tuple = (10, 20, "red")
x, y, color = my_tuple # Unpacking: x=10, y=20, color="red"
```
---
### **3. Dictionary**
- **Description**: Unordered, mutable, stores **key-value pairs**.
- **Use Case**: Fast lookups (e.g., mapping user IDs to names).
- **Example**:
```python
my_dict = {"name": "Alice", "age": 30}
my_dict["email"] = "alice@example.com" # Add new key-value pair
print(my_dict["name"]) # Output: Alice
```
---
### **4. Set**
- **Description**: Unordered, mutable, **unique elements**, no duplicates.
- **Use Case**: Membership testing, removing duplicates from a list.
- **Example**:
```python
my_set = {1, 2, 3}
my_set.add(3) # No change (3 already exists)
my_set.remove(2) # Result: {1, 3}
```
---
### **5. String**
- **Description**: Immutable sequence of Unicode characters.
- **Use Case**: Text manipulation.
- **Example**:
```python
text = "Hello, World!"
print(text[0:5]) # Slicing: "Hello"
new_text = text.replace("World", "Python")
```
---
### **6. Advanced Data Structures (from `collections` module)**
#### **Deque**
- **Description**: Double-ended queue for fast appends/pops from both ends.
- **Use Case**: Implementing queues or stacks.
- **Example**:
```python
from collections import deque
queue = deque([1, 2, 3])
queue.append(4) # Add to end: deque([1, 2, 3, 4])
queue.popleft() # Remove from front: deque([2, 3, 4])
```
#### **Named Tuple**
- **Description**: Tuple with named fields for readability.
- **Example**:
```python
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, y=20)
print(p.x) # Output: 10
```
---
### **7. Heap (Priority Queue)**
- **Description**: Binary heap for efficient min/max operations.
- **Use Case**: Scheduling tasks by priority.
- **Example**:
```python
import heapq
heap = []
heapq.heappush(heap, 3) # Add elements
heapq.heappush(heap, 1)
print(heapq.heappop(heap)) # Output: 1 (smallest element)
```
---
### **8. Custom Data Structures**
- **Linked List/Graph/Tree**: Implemented using classes or dictionaries.
- **Example** (Linked List Node):
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
node1 = Node(1)
node2 = Node(2)
node1.next = node2
```
---
### **Key Takeaways**
- **Lists/Tuples**: Order matters.
- **Dictionaries/Sets**: Fast lookups by key or membership checks.
- **Strings**: Immutable, use slicing for manipulation.
- **Use `collections`/`heapq`**: For specialized use cases (queues, heaps).
Let me know if you'd like further details on any specific structure! 🐍
Comments
Post a Comment