Skip to content

Python set() Function

How to create a set from iterables like strings, tuples, lists, dictionaries, or ranges using Python's built-in set() constructor, including handling duplicates and empty sets.

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)

Syntax

set(iterable)

set() Parameters

Python set() function parameters:

Parameter Condition Description
iterable Optional A 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

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'}

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}
Navigation