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 that provides a host of benefits, including:

  • Deploy your application in seconds with a simple git push.
  • Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
  • Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
  • Get optimal performance and robust security thanks to a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's Python cloud hosting solution!

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})