Python set()
Function
The set() function in Python is used to create a set object. A set is an unordered collection of unique items — meaning it automatically removes duplicates.
Syntax
set([iterable])
Parameters:
iterable
– (Optional) Any iterable such as list, tuple, string, or dictionary keys.
Returns:
- A new
set
object containing unique elements.
Example 1: Convert a List to a Set
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3, 4, 5}
Example 2: Create a Set from a String
text = "banana"
letters = set(text)
print(letters)
{'b', 'a', 'n'}
Note: The order may vary because sets are unordered.
Example 3: Empty Set
empty = set()
print(empty)
set()
Warning: Using {}
creates an empty dict
, not a set
.
Use Cases of set()
- Remove duplicates from a list
- Check for unique items
- Perform set operations like union, intersection, difference
Example 4: Removing Duplicates Using set()
data = ["apple", "banana", "apple", "cherry"]
unique_fruits = list(set(data))
print(unique_fruits)
['banana', 'cherry', 'apple']
(Order may vary)
Common Mistakes
{}
is an empty dictionary, not a set — useset()
for an empty set- Sets do not support indexing or slicing
- Items in a set must be hashable (e.g., no lists)
Interview Tip
set()
is often used in coding problems involving uniqueness, duplicates, or fast lookups without ordering.
Summary
set()
converts iterables into a set of unique elements- Used to remove duplicates or perform set operations
- Unordered and unindexed collection
- Use
set()
, not{}
, to create an empty set
Practice Problem
Write a program to read 5 names from the user and display only the unique names entered.
names = []
for _ in range(5):
names.append(input("Enter a name: "))
print("Unique names:", set(names))