Python: Collections module
This documentation is part of the Learning Python guide. You can view the complete guide here: A comprehensive Python guide.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Python cloud solution designed to simplify your deployments:
- Deploy your application to production within seconds using a simple
git push.- Use your own domain name, with automatic HTTPS certificate setup for secure connections managed on your behalf.
- Take advantage of automatic backups, one-click updates, and predictable pricing, so you can focus on your code rather than infrastructure management.
- Benefit from high performance and security on a private, dedicated infrastructure. Your environment is isolated and protected.
Save time and streamline your workflow: your code can be up and running with Stackhero's Python cloud hosting in just 5 minutes.
The collections module offers specialised container data types that can help improve your programmes.
from collections import namedtuple, defaultdict, Counter, deque
Examples:
from collections import namedtuple, deque, Counter, OrderedDict, defaultdict
# namedtuple
Person = namedtuple('Person', 'name age')
person1 = Person("Alice", 30)
print(person1.name, person1.age) # Output: Alice 30
# deque
dq = deque([1, 2, 3, 4, 5])
dq.append(6)
dq.appendleft(0)
print(dq) # Output: deque([0, 1, 2, 3, 4, 5, 6])
# Counter
count = Counter("hello world")
print(count) # Output: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od) # Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# defaultdict
dd = defaultdict(int)
dd['a'] += 1
dd['b'] += 2
print(dd) # Output: defaultdict(<class 'int'>, {'a': 1, 'b': 2})