Set() Function In Python

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:

# 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:

{'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.


Copyright 2018 © pythontic.com