Sobes.tech
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:

    • set stores only unique elements, duplicates are automatically removed.
    • list can 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).
  • 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.
  • Performance:

    • Checking for the presence of an element in set is faster (O(1)) due to hashing.
    • In list, the check takes O(n).

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
How do set and list collections differ in their work… - sobes.tech