Common Collections Usage
namedtuple: Creating Lightweight Objects
from collections import namedtuple
## Define a Point with x and y coordinates
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) ## Output: 10 20
deque: Efficient Double-Ended Queue
from collections import deque
## Create a double-ended queue
d = deque([1, 2, 3])
d.appendleft(0) ## Add to left
d.append(4) ## Add to right
print(d) ## Output: deque([0, 1, 2, 3, 4])
Counter: Counting and Tracking Occurrences
from collections import Counter
## Count word frequencies
words = ['apple', 'banana', 'apple', 'cherry']
word_count = Counter(words)
print(word_count) ## Output: Counter({'apple': 2, 'banana': 1, 'cherry': 1})
OrderedDict: Maintaining Insertion Order
from collections import OrderedDict
## Create an ordered dictionary
od = OrderedDict()
od['first'] = 1
od['second'] = 2
od['third'] = 3
for key, value in od.items():
print(key, value)
defaultdict: Simplified Dictionary Initialization
from collections import defaultdict
## Create a defaultdict with list as default factory
dd = defaultdict(list)
dd['users'].append('Alice')
dd['users'].append('Bob')
print(dd) ## Output: defaultdict(<class 'list'>, {'users': ['Alice', 'Bob']})
Collection Usage Patterns
graph TD
A[Collections Usage] --> B[Data Counting]
A --> C[Efficient Storage]
A --> D[Order Preservation]
B --> E[Counter]
C --> F[deque]
D --> G[OrderedDict]
Practical Scenarios
Collection Type |
Use Case |
Example |
namedtuple |
Lightweight data structures |
Representing coordinates |
deque |
Efficient queue operations |
Task scheduling |
Counter |
Frequency analysis |
Word counting |
OrderedDict |
Maintaining order |
Configuration settings |
defaultdict |
Simplified dictionary |
Grouping data |
- Choose the right collection for specific tasks
- Consider memory and time complexity
- Leverage built-in methods
LabEx Recommendation
Practice these collections in real-world scenarios to master their usage and improve your Python programming skills.