PYTHON

Collection Modules


The collections module in Python provides several specialized container datatypes:

 

1. Named Tuples

Named tuples are a subclass of tuples with named fields. They are useful for creating simple classes with minimal overhead.

Example:

from collections import namedtuple
# Define a named tuple
Point = namedtuple('Point', ['x', 'y'])
# Create an instance of Point
p = Point(11, 22)
print(p.x, p.y)  # Output: 11 22

 

 

2. Defaultdict

Defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. It provides a default value for the key that does not exist.

Example:

from collections import defaultdict
# Define a defaultdict with default type int
dd = defaultdict(int)
# Accessing a non-existing key will return the default value (0 in this case)
dd['key'] += 1
print(dd)  # Output: defaultdict(<class 'int'>, {'key': 1})
 

 

3. Counter

Counter is a subclass of dict that is used to count hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

Example:

from collections import Counter
# Create a Counter from a list
cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(cnt)  # Output: Counter({'blue': 3, 'red': 2, 'green': 1})
# Access counts
print(cnt['blue'])  # Output: 3
 

 

4. OrderedDict

OrderedDict is a dictionary that remembers the order of the items inserted. The order is preserved when iterating over the dictionary.

Example:

from collections import OrderedDict
# Create an OrderedDict
od = OrderedDict()
od['first'] = 1
od['second'] = 2
od['third'] = 3
# Iterate over OrderedDict
for key, value in od.items():
   print(key, value)
# Output:
# first 1
# second 2
# third 3
 

 

5. deque

Deque (double-ended queue) is a list-like container with fast appends and pops on either end.

Example:

from collections import deque

# Create a deque
d = deque([1, 2, 3])
d.append(4)
d.appendleft(0)
print(d)  # Output: deque([0, 1, 2, 3, 4])
# Pop elements from both ends
d.pop()
d.popleft()
print(d)  # Output: deque([1, 2, 3])
 

 


PYTHON