What collections (data structures) are there in Python?
sobes.tech AI
Answer from AI
In Python, there are several built-in collections (data structures) that are widely used for storing and processing data:
-
list — an ordered, mutable list of elements. Allows storing elements of different types, supports indexing, slicing, adding, and removing elements.
-
tuple — an ordered, immutable set of elements. Used when data immutability needs to be guaranteed.
-
set — an unordered collection of unique elements. Enables quick membership testing, and supports union, intersection, and difference operations.
-
dict — a dictionary, an associative array that stores key-value pairs. Keys must be hashable, values can be of any type.
Additionally, the collections module provides additional structures:
-
deque — a double-ended queue with fast appends and pops from both ends.
-
defaultdict — a dictionary with a default value for missing keys.
-
OrderedDict — a dictionary that preserves the order of insertion (in newer Python versions, the built-in dict also preserves order).
-
Counter — a dictionary subclass for counting hashable objects.
Example of using list and dict:
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
prices = {'apple': 100, 'banana': 80}
prices['cherry'] = 120
print(fruits) # ['apple', 'banana', 'cherry', 'date']
print(prices['banana']) # 80