As you progress in your Python journey, you'll encounter scenarios where the basic data structures like lists, tuples, dictionaries, and sets might not be the most efficient or convenient choice. This section offers a brief overview of some more advanced data structures that Python and its extensive libraries provide, or that you can build yourself, to tackle complex problems.
While Python's built-in structures are incredibly powerful, the collections module in the standard library offers specialized container datatypes that provide alternatives to Python's general-purpose built-ins. These are often more efficient for specific use cases and can make your code cleaner and more readable.
Let's explore a few key ones:
collections.Counter: A subclass ofdictthat's specifically designed for counting hashable objects. It's perfect for tallying frequencies of items in a sequence.
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counts = Counter(my_list)
print(counts)collections.deque: A double-ended queue that allows for efficient appends and pops from both ends. It's a great alternative to lists when you need to perform many operations at the beginning of a sequence.
from collections import deque
d = deque(['a', 'b', 'c'])
d.appendleft('z')
d.append('y')
print(d)collections.namedtuple: Creates tuple-like objects with named fields, making your code more readable and self-documenting. You can access elements by name instead of just by index.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)collections.defaultdict: A subclass ofdictthat calls a factory function to supply missing values. This is useful when you want to avoid checking if a key exists before accessing or modifying it.