Python sets are a built-in data structure used to store unique elements. They are unordered and mutable, making them ideal for removing duplicates, performing set operations, and checking membership. In this guide, you'll learn multiple ways to create sets with simple, human-readable examples.
1. What is a Set?
A set is an unordered collection of unique and immutable elements. However, the set itself is mutable — you can add or remove items after creation. Sets do not allow duplicate values.
2. Creating a Set Using Curly Braces
You can create a set using curly braces {}
by listing the elements you want to include.
# Example 1: Creating a set with curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Note: The order may change because sets are unordered.
3. Creating a Set Using the set() Constructor
The set()
function can be used to create a set from any iterable such as a list, tuple, or string.
# Example 2: Creating a set from a list
numbers = set([1, 2, 3, 2, 1])
print(numbers) # Output: {1, 2, 3}
# Example 3: Creating a set from a string
chars = set("hello")
print(chars) # Output: {'h', 'e', 'l', 'o'}
4. Creating an Empty Set
To create an empty set, always use set()
. Using {}
creates an empty dictionary, not a set.
# Example 4: Creating an empty set
empty_set = set()
print(empty_set) # Output: set()
print(type(empty_set)) # Output: <class 'set'>
# Example 5: Incorrect way (creates a dictionary)
empty_dict = {}
print(type(empty_dict)) # Output: <class 'dict'>
5. Sets Remove Duplicates Automatically
When creating a set, duplicate values are automatically removed.
# Example 6: Duplicate removal
data = set([1, 2, 2, 3, 3, 3])
print(data) # Output: {1, 2, 3}
6. Creating a Set from a Tuple
# Example 7: Set from a tuple
tuple_data = (10, 20, 30, 10)
unique_numbers = set(tuple_data)
print(unique_numbers) # Output: {10, 20, 30}
7. Set with Mixed Data Types
Sets can store elements of different data types as long as they are immutable.
# Example 8: Mixed data types
mixed = {"hello", 42, 3.14, True}
print(mixed)
Important Rules When Creating Sets
- Sets can only contain hashable (immutable) elements like numbers, strings, and tuples.
- Lists and other sets cannot be added to a set as elements.
# Example 9: Invalid set (will raise error)
# invalid_set = {1, 2, [3, 4]} # Raises TypeError
Summary
- Use
{}
orset()
to create sets. - Use
set()
to convert lists, tuples, or strings into sets. - Use
set()
for creating empty sets —{}
creates a dictionary. - Sets automatically remove duplicate elements and store only unique values.
Final Thoughts
Understanding how to create sets in Python is essential for working with collections of unique items. Whether you're removing duplicates from data or performing advanced set operations, sets offer a clean, efficient solution that's easy to implement.