set() function in Python

The built-in function set() in Python creates an unordered collection of non-duplicate elements representing the mathematical concept of set.

Built-in Functions Updated 7 Mar 2017 1 min read

Function Name

set

Function Signature

set([iterable])

Function Overview

  • The function set() is the constructor to the Python class set.

  • The set() function creates and returns an empty set or it returns a set with the contents from an iterable object.

  • Since a set object is mutable, it does not have a hash value.

  • Sets do no support indexing and slicing operations.

  • The elements in a set are not sorted.

Example

python
# set object initialised with a tuple

colors = set(("red","red","red","blue","green","green"))

print(colors)

# set of prime numbers less than ten

primeTuple = (2,3,5,7)

primeSet = set(primeTuple)

print(primeSet)

Output

Output
{'green', 'blue', 'red'}

{2, 3, 5, 7}

Note that the colors set does not have multiple values of red and green as the source tuple it was initialized with, because a set will not have duplicate values.