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:
- Remove duplicates automatically.
- Perform mathematical set operations (like union, intersection, difference, etc.).
Python
# Creating a set using curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits) Note:
- Sets use curly braces {}, similar to dictionaries, but without key-value pairs.
- Duplicates are removed automatically:
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'>