Sets in Python
Sets are a collection type in Python that, unlike lists or tuples, are unordered, unchangeable (though you can add or remove items), and do not allow duplicate elements. Sets are defined by placing items inside curly braces {}
, separated by commas.
Creating a Set:
Python
# Creating a set
fruits = {"apple", "banana", "cherry"}
# Sets automatically remove duplicates
unique_numbers = {1, 2, 3, 1, 2}
print(unique_numbers) # Output: {1, 2, 3}
# Empty set (note: {} creates a dictionary, not a set)
empty_set = set()
Sets are commonly used for operations involving uniqueness, like finding distinct items in a list.
Import Links
Here are some useful import links for further reading: