Sets in Python

What is a Set? A set in Python is a collection of unique, unordered elements, unindexed collection of elements. Unindexed means that the elements cannot access elements by index.

It is useful when you want to:

Python

# Creating a set using curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits)

Note:

Python

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

Creating an Empty Set Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we use the set() function without any argument.

Python

# Wrong way (this creates a dictionary)
# Initialize with {}

empty_set = {}

# check data type
print(type(empty_set))  # Output: <class 'dict'>

# Correct way
# Initialize with set()
empty_set = set()
print(type(empty_set))  # Output: <class 'set'>