Junior — Middle
How do set and list collections differ in their work and usage in Python?
sobes.tech AI
Answer from AI
Main differences between set and list collections in Python:
-
Uniqueness of elements:
setstores only unique elements, duplicates are automatically removed.listcan contain repeated elements.
-
Order of elements:
- In
list, the order of addition is preserved. - In
set, order is not guaranteed (starting from Python 3.7, insertion order is preserved, but it should not be relied upon).
- In
-
Access by index:
- In
list, you can access elements by index, e.g.,my_list[0]. - In
set, there are no indices, elements are iterated in arbitrary order.
- In
-
Performance:
- Checking for the presence of an element in
setis faster (O(1)) due to hashing. - In
list, the check takes O(n).
- Checking for the presence of an element in
Example:
my_list = [1, 2, 2, 3]
my_set = {1, 2, 2, 3}
print(my_list) # [1, 2, 2, 3]
print(my_set) # {1, 2, 3}
print(2 in my_list) # True
print(2 in my_set) # True
print(my_list[1]) # 2
# print(my_set[1]) # Error, set cannot be indexed