set() Constructor in Python
Last Updated :
10 Nov, 2024
Improve
In Python, the set()
constructor is used to create a set object. A set is a built-in data type that stores an unordered collection of unique elements. The set()
constructor can be used to create an empty set or convert other data types (like lists, tuples, or strings) into a set.
Example:
# Example of set constructor
a = set() # creates an empty set
b = set([1, 2, 2, 3]) # converts a list into a set
c = set("hello") # converts a string into a set
print(a, type(a))
print(b, type(b))
print(c, type(c))
9
1
# Example of set constructor
2
3
a = set() # creates an empty set
4
b = set([1, 2, 2, 3]) # converts a list into a set
5
c = set("hello") # converts a string into a set
6
7
print(a, type(a))
8
print(b, type(b))
9
print(c, type(c))
Output
set() <class 'set'> {1, 2, 3} <class 'set'> {'o', 'l', 'h', 'e'} <class 'set'>
Syntax of set()
set([iterable])
- iterable: This is an optional argument. If provided, it should be an iterable object (like a list, tuple, or string). The
set()
function will convert this iterable into a set. - If no iterable is passed,
set()
will create an empty set.
Use of set() Constructor
The set()
constructor is commonly used for:
- Creating an empty set.
- Converting other data types (like lists, tuples, or strings) into sets.
- Storing unique elements (duplicates are automatically removed).
Let’s explore a few examples to understand how this works in practice.
Convert a List to a Set
If you have a list with some duplicate values, you can convert it into a set to remove duplicates:
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list)
print(unique_set)
3
1
my_list = [1, 2, 2, 3, 4, 4, 5]
2
unique_set = set(my_list)
3
print(unique_set)
Output
{1, 2, 3, 4, 5}
Convert a String to a Set
When you convert a string to a set, each character in the string becomes an individual element of the set:
my_string = "banana"
unique_chars = set(my_string)
print(unique_chars)
3
1
my_string = "banana"
2
unique_chars = set(my_string)
3
print(unique_chars)
Output
{'n', 'a', 'b'}