Skip to main content

Python set() Function

The set() constructor creates a set object from an iterable.

The iterable may be a sequence (such as a string, tuple or range) or a collection (such as a dictionary, set or frozen set)

note

A Set is an unordered collection of unique elements. So, you will not have duplicates in the resulting Set!

Syntax

set(iterable)

set() Parameters

Python set() function parameters:

ParameterConditionDescription
iterableOptionalA sequence or a collection

set() Return Value

Python set() function returns a set:

  • If no parameters are passed, it returns an empty set
  • If iterable is passed as a parameter, it creates a set consisting of iterable's items without duplicates.

Examples

note

The order of elements in the resulting Set may vary since a Set is an unordered collection of elements!

Example 1: Creating an Empty Set

Let's create an empty Set using set() without argument.

empty_set = set()
print(empty_set) # Output: set()

output

set()

Example 2: Creating a Set from a String

Let's create a Set from a String using set():

string = "ABCDE"
my_set = set(string)
print(my_set) # Output: {'A', 'E', 'C', 'B', 'D'}

output

{'A', 'E', 'C', 'B', 'D'}

Example 3: Creating a Set from a Tuple

Let's covert a Tuple to a Set using set():

tuple1 = ('A', 'B', 'C', 'D', 'E')
my_set = set(tuple1)
print(my_set) # Output: {'B', 'E', 'C', 'A', 'D'}

output

{'B', 'E', 'C', 'A', 'D'}

Example 4: Creating a Set from a Set

Let's create a Set from a Set using set():

set1 = {1,  2,  3,  4,  5}
my_set = set(set1)
print(my_set) # Output: {1, 2, 3, 4, 5}

output

{1,  2,  3,  4,  5}

Example 5: Creating a Set from a Dictionary

Let's convert a Dictionary to a Set using set():

dict1 = {'one':  1, 'two':  2, 'three':  3}
my_set = set(dict1)
print(my_set) # Output: {'two', 'three', 'one'}

output

{'two', 'three', 'one'}
note

The resulting set will be made of the keys of the given dictionary!

Example 6: Creating a Set from a List

Let's convert a List to a Set using set():

list1 = ['a', 'b', 'c', 'd', 'e']
new_list = set(list1)
print(new_list) # Output: {'e', 'c', 'a', 'b', 'd'}

output

{'e', 'c', 'a', 'b', 'd'}

Example 7: Creating a Set from a Range

Let's convert a Range to a Set using set():

list1 = set(range(0, 5))
print(list1) # Output: {0, 1, 2, 3, 4}

output

{0, 1, 2, 3, 4}