Junior — Middle
Can you name the main data structures from the collections module in Python and tell about them?
sobes.tech AI
Answer from AI
The Python collections module includes several useful data structures:
-
namedtuple — a tuple with named fields, convenient for creating lightweight objects.
-
deque — a double-ended queue, efficient for adding and removing elements from both ends.
-
Counter — a dictionary for counting the number of occurrences of elements in an iterable.
-
OrderedDict — a dictionary that preserves the order of insertion (before Python 3.7, now a regular dict also preserves order).
-
defaultdict — a dictionary with a default value for non-existent keys.
Example of using Counter:
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
c = Counter(words)
print(c) # Counter({'apple': 3, 'banana': 2, 'orange': 1})