Junior — Middle
Can you explain what a set is in Python and what its main purpose is?
sobes.tech AI
Answer from AI
In Python, a set is an unordered collection of unique elements. The main purpose of a set is to store unique values and perform operations on them, such as union, intersection, difference, and symmetric difference.
Example of using a set:
fruits = {'apple', 'banana', 'orange'}
fruits.add('kiwi') # adding an element
fruits.add('apple') # will not be added, since 'apple' already exists
print(fruits) # outputs the unique fruits
# set operations
set_a = {1, 2, 3}
set_b = {2, 3, 4}
print(set_a & set_b) # intersection: {2, 3}
print(set_a | set_b) # union: {1, 2, 3, 4}
print(set_a - set_b) # difference: {1}