Python Program to Create a Set

Write a Python program to create a set. In this example, we create an empty set and print the same. Although both look correct, the first one returns the dictionary, not an empty set.

# Create an Empty Set

s1 = {}
print(s1)

s2 = set()
print(s2)

Empty set output

{}
set()
>>> 

In this example, we created different sets using both the {} and Python set() function. Please refer to the Python tutorial and the Python basic program articles.

# Create a Set

s1 = {2, 4, 6, 8, 10}
print(s1)
print(type(s1))

s2 = set(['USA', 'China', 'UK', 'Russia', 'India', 'France'])
print(s2)
print(type(s2))

s3 = set("Tutorial Gateway")
print(s3)
print(type(s3))
Program to Create a Set

The following program creates a set from a list. It uses the built-in set() method to create a new set from an existing list.

l = [1, 2, 3, 4, 5, 6]
s = set(l)
print(s)
print(type(s))
{1, 2, 3, 4, 5, 6}
<class 'set'>

This program creates a set of mixed elements, including a string, number, floating-point value, and Boolean value.

s = {"Hi", 10, True, "Live", 20.52, 50}
print(s)
{True, 50, 20.52, 10, 'Live', 'Hi'}

Also Read