set() Function in python
set() function in Python is used to create a set, which is an unordered collection of unique elements. Sets are mutable, meaning elements can be added or removed after creation. However, all elements inside a set must be immutable, such as numbers, strings or tuples. The set() function can take an iterable (like a list, tuple or dictionary) as input, removing duplicates automatically. Sets support various operations such as union, intersection and difference, making them useful for mathematical computations and data processing.
Example:
a = set([1, 2, 3, 4, 2, 3])
print(a)
Output
{1, 2, 3, 4}
Syntax:
set(iterable)
here, iterable can be anything like list, tuple, dictionary or range. If no argument is provided it will create an empty set.
1. Creating an empty set
In Python, an empty set can be created using the set()
function, as curly braces {}
create an empty dictionary instead. An empty set is useful for storing unique elements dynamically. Since sets are mutable, elements can be added later using add()
or update()
. The type()
function can be used to verify the data type.
a = set()
print(a)
print(type(a))
Output
set() <class 'set'>
It will return the empty set.
2. set with list
A list can be converted into a set using set
()
. This removes duplicate elements and stores only unique values. Since sets are unordered, the order of elements in the original list may not be preserved. This method is useful for filtering out duplicate values from a list.
a = [1, 2, 3, 4, 2, 3, 5]
b = set(a)
print(b)
Output
{1, 2, 3, 4, 5}
List is converted into set.
3. set with tuple()
Tuples, like lists, can be converted into sets using the set() function. Since sets only store unique elements, duplicates from the tuple are removed. This is useful when needing a unique collection of immutable values. The resulting set is unordered and does not retain the tuple’s order.
tup = (1, 2, 3, 4, 2, 3, 5)
a = set(tup)
print(a)
Output
{1, 2, 3, 4, 5}
tuple is converted into a set.
4. set with range()
A set can be created using the range() function, which generates a sequence of numbers. When passed to set(), it produces a set containing the unique numbers in the specified range. This method is useful for quickly generating sets of consecutive numbers.
a = set(range(0, 11))
print(a)
Output
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
range function is used to create set.
5. set with dictionary
When a dictionary is converted into a set using set()
, only the keys are stored in the set. The values are ignored unless explicitly extracted and converted. This method is useful when working with unique keys from a dictionary.
d = {'a': 1, 'b': 2, 'c': 3}
a = set(d)
print(a)
Output
{'b', 'a', 'c'}
Output order may vary.