Python set() function

The set() function in Python is used when we need to create a set object. For example:

myset = set(('codes', 'cracker', 'dot', 'com'))

print(type(myset))
print(myset)

The output is:

<class 'set'>
{'cracker', 'com', 'dot', 'codes'}

Python set() function syntax

The syntax of the set() function in Python is:

where iterable refers to a collection, a sequence, or an iterator object.

Note: If no parameter(s) is/are passed to set(), then an empty set will be returned by this function.

Python set() function example

Here is an example of the set() function in Python:

s = set()
print(s)

x = [12, 4, 54]
s = set(x)
print(s)

x = (12, 32, 54, 65)
s = set(x)
print(s)

x = {"Day": "Sat", "Month": "Dec"}
s = set(x)
print(s)

The output is:

set()
{12, 4, 54}
{32, 65, 12, 54}
{'Day', 'Month'}

Note: If set is created from a dictionary object, then the key will become an element of set.

Advantages of the set() function in Python

  • The set() function in Python makes it simple to create a set object, which can be used to store a collection of unique elements.
  • By converting a list or other iterable to a set and then back to a list, the set() function can be used to remove duplicates.
  • Python set objects are iterable and support common set operations like union, intersection, and difference.

Disadvantages of the set() function in Python

  • The elements of sets in Python are not stored in a particular order because sets are unordered. This might not be a good thing if the order of the components matters.
  • Set objects can be altered after being created because they are mutable. If you need to store a collection of immutable objects, this could be a drawback.
  • Since the set() function iterates through each element and looks for duplicates, it can be computationally expensive for large or complex iterables.

Python Online Test


« Previous Function Next Function »



Liked this post? Share it!