In addition to lists and tuples, Python has a collection type called Set (set) for handling groups of data. Based on the mathematical concept of sets, the set type has two very important characteristics:
- No Duplicate Elements: If you try to add the same element multiple times, it is automatically combined into one.
- Unordered: It does not maintain a specific order.
Sets are used to efficiently remove duplicate elements from a list, perform high-speed existence checks, or perform set operations (like union and intersection).
This article explains the basic ways to create sets.
1. Creating with {} (Curly Braces)
The basic way to create a set is to enclose elements in {} (curly braces), separated by commas.
# Create a set with curly braces
# Note that "web" is duplicated
tags = {"python", "django", "web", "api", "web"}
print(tags)
print(f"Type: {type(tags)}")
Output:
{'api', 'python', 'django', 'web'}
Type: <class 'set'>
(Note: The order of elements in the output may vary depending on the environment.)
The duplicate “web” was automatically removed, and the set was created with only unique elements.
2. Creating with set() Constructor (Converting from List)
A very common use case for sets is removing duplicate elements from a list. By passing an iterable (like a list) to the set() constructor (function), it converts it into a set with duplicates removed.
# List of user IDs containing duplicates
user_id_list = ["u001", "u002", "u001", "u003", "u002", "u001"]
print(f"Original List: {user_id_list}")
# Convert list to set using set() to remove duplicates
unique_user_ids = set(user_id_list)
print(f"After Deduplication (set): {unique_user_ids}")
Output:
Original List: ['u001', 'u002', 'u001', 'u003', 'u002', 'u001']
After Deduplication (set): {'u002', 'u003', 'u001'}
If you want to treat it as a list again after removing duplicates, you can convert it back using list(set(user_id_list)).
3. How to Create an Empty Set (Important)
This is the most important point to remember when creating sets. If you try to create an empty set using only {} (curly braces), Python interprets it as an Empty Dictionary (dict).
# This becomes an empty "Dictionary"
empty_wrong = {}
print(f"Type of {{}}: {type(empty_wrong)}")
Output:
Type of {}: <class 'dict'>
To create an empty set, you must call the set() constructor without arguments.
# The correct way to create an empty set
empty_correct = set()
print(f"Type of set(): {type(empty_correct)}")
Output:
Type of set(): <class 'set'>
Summary
setis a data type that does not allow duplicates and is unordered.- You can create one using
{}like{"a", "b", "c"}. - Using
set(list)allows you to easily remove duplicate elements from a list. - To create an empty set, use
set(), not{}.
