Middle
215
What collections exist in Python and what are their features in terms of speed and memory usage?
Answer from AI
sobes.tech AI
In Python, there are several built-in collections (data structures) for storing and organizing data. The main ones:
- list: An ordered, mutable collection that can store elements of different types. Access by index O(1). Insertion/deletion at the end O(1), in the middle/start O(n). Uses more memory than a tuple due to flexibility.
- tuple: An ordered, immutable collection. Faster than lists for iteration and index access O(1). Insertion/deletion is impossible. Uses less memory than a list, as it is fixed.
- set: An unordered, mutable collection of unique elements. Supports set operations (union, intersection, difference). Adding/removing and membership testing O(1) on average. Uses hashing, which may require more memory than list/tuple for small numbers of elements but is efficient for large datasets with unique elements.
- frozenset: An unordered, immutable collection of unique elements. Similar to
set, but cannot be changed after creation. Can be used as a key in a dictionary or as an element of another set. - dict: An unordered, mutable collection of key-value pairs. Keys must be hashable (immutable, e.g., strings, numbers, tuples). Access, addition, and removal by key O(1) on average. Uses hashing, requires more memory than list/tuple but provides fast key-based access.
| Collection | Ordered | Mutable | Unique elements | Speed (index/key access) | Speed (insertion/deletion) | Memory usage |
|---|---|---|---|---|---|---|
| list | Yes | Yes | No | O(1) | O(1) (end), O(n) (middle/start) | Average |
| tuple | Yes | No | No | O(1) | N/A | Less (than list) |
| set | No | Yes | Yes | N/A | O(1) (average) | Average (for hashing) |
| frozenset | No | No | Yes | N/A | N/A | Average (for hashing) |
| dict | No (in older versions, ordered in 3.7+) | Yes | Unique keys | O(1) (average) | O(1) (average) | Larger (for hashing) |
# Collection examples
my_list = [1, 2, 'hello'] # List
my_tuple = (1, 2, 'world') # Tuple
my_set = {1, 2, 2, 'hello'} # Set (duplicates removed)
my_frozenset = frozenset({1, 2, 'immutable'}) # Frozenset
my_dict = {'a': 1, 'b': 2} # Dictionary