Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Container Datatypes
Python's collections module provides specialized container datatypes that serve as alternatives to built-in containers like dict, list, and set. These containers offer enhanced functionality and performance for specific use cases.
Collections Module Container Types
| Container | Description |
|---|---|
| namedtuple() | Creates tuple subclasses with named fields for better readability |
| deque | Double-ended queue optimized for adding/removing from both ends |
| Counter | Dict subclass for counting hashable objects |
| ChainMap | Creates a single view of multiple mappings |
| OrderedDict | Dict that remembers insertion order (deprecated in Python 3.7+) |
| UserList | Wrapper around list objects for easier subclassing |
To use these containers, import the collections module −
import collections
Deque (Double-ended Queue)
A deque is a generalization of stacks and queues that supports efficient additions and deletions from both ends.
Key Deque Methods
| Method | Description |
|---|---|
append(x) |
Add element x to the right side |
appendleft(x) |
Add element x to the left side |
pop() |
Remove and return element from right side |
popleft() |
Remove and return element from left side |
rotate(n) |
Rotate deque n steps to the right |
Example
import collections as col
my_deque = col.deque('124dfre')
print("Initial deque:", my_deque)
print("Popped Item:", my_deque.pop())
print("Popped Item From Left:", my_deque.popleft())
print("Final deque:", my_deque)
Initial deque: deque(['1', '2', '4', 'd', 'f', 'r', 'e']) Popped Item: e Popped Item From Left: 1 Final deque: deque(['2', '4', 'd', 'f', 'r'])
Counter Object
A Counter is a dict subclass for counting hashable objects. It's useful for tallying occurrences of elements.
Key Counter Methods
| Method | Description |
|---|---|
most_common(n) |
Return n most common elements and their counts |
elements() |
Return iterator over elements repeating each as many times as counted |
update() |
Add counts from another iterable or mapping |
subtract() |
Subtract counts from another iterable or mapping |
Example
import collections as col
text_list = ['ABC', 'PQR', 'ABC', 'ABC', 'PQR', 'Mno', 'xyz', 'PQR', 'ABC', 'xyz']
my_counter = col.Counter(text_list)
print("Counter:", my_counter)
print("Most common 2:", my_counter.most_common(2))
Counter: Counter({'ABC': 4, 'PQR': 3, 'xyz': 2, 'Mno': 1})
Most common 2: [('ABC', 4), ('PQR', 3)]
ChainMap Object
A ChainMap groups multiple dictionaries together to create a single, updatable view.
Example
import collections as col
con_code1 = {'India': 'IN', 'China': 'CN'}
con_code2 = {'France': 'FR', 'United Kingdom': 'GB'}
code = {'Japan': 'JP'}
chain = col.ChainMap(con_code1, con_code2)
print("Initial Chain:", chain.maps)
chain = chain.new_child(code) # Insert new dictionary at front
print("Final Chain:", chain.maps)
Initial Chain: [{'India': 'IN', 'China': 'CN'}, {'France': 'FR', 'United Kingdom': 'GB'}]
Final Chain: [{'Japan': 'JP'}, {'India': 'IN', 'China': 'CN'}, {'France': 'FR', 'United Kingdom': 'GB'}]
Conclusion
Python's collections module provides specialized containers like deque for efficient queue operations, Counter for counting elements, and ChainMap for combining dictionaries. These containers offer better performance and functionality than using built-in types for specific tasks.
