Skip to content

Set function in Python | Basics

  • by

The Python set() function is used to create a new set. You can create an empty set or set with elements passed during the call.

This function takes iterable as an argument and returns a new set object.

set(iterable) 

Examples Set function in Python

Simple example code creates a set using a set function.

set1 = set()  # empty set
set2 = set('21')
set3 = set({1, 2, 3})

# Displaying result  
print(set1)
print(set2)
print(set3)

Output:

Set function in Python

Another example

Create a set of using iterable elements like lists, tuples, dictionaries, and strings. Python set() function is used to convert any of the iterable to the sequence of iterable elements with distinct elements, commonly called Set.

set1 = set(['12', '13', '15'])  # List

set2 = set(('A', 'B', 'C'))  # tuple

set3 = set({1: 'One', 2: 'Two', 3: 'Three'})  # dictionary

set4 = set('Hello')  # Strings

print(set1)
print(set2)
print(set3)
print(set4)

Output:

{’12’, ’13’, ’15’}
{‘A’, ‘C’, ‘B’}
{1, 2, 3}
{‘H’, ‘e’, ‘o’, ‘l’}

Do comment if you have any doubts or suggestions on this Python basic set topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *