Python Set Explained with Examples

Python set is an unordered collection of unique elements.

Creating Sets

You can create a python set using curly braces {} or the set().

# Creating a set with integers
my_set = {1, 2, 3, 4}

# Creating a set with strings
my_string_set = {"apple", "banana", "cherry"}

# Creating an empty set
empty_set = set()

Unique Elements

Sets contain only unique elements. Duplicate elements are automatically removed.

my_set = {1, 2, 3, 3, 2}
print(my_set)  # Output: {1, 2, 3}

Iterating Over Sets

You can use for in loop to iterate each element in a set.

for e in my_set:
print(e)