Python: Create a new empty set
1. Create a Set
Write a Python program to create a set.
From Wikipedia,
In mathematics, a set is a collection of distinct elements. The elements that make up a set can be any kind of things: people, letters of the alphabet, numbers, points in space, lines, other geometrical shapes, variables, or even other sets. Two sets are equal if and only if they have precisely the same elements

To create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.
Sample Solution:
Python Code:
# Create a new set:
print("Create a new set:")
# Initialize an empty set and assign it to the variable 'x':
x = set()
# Print the empty set 'x':
print(x)
# Print the data type of 'x', which should be 'set':
print(type(x))
# Print a newline for separation:
print("\nCreate a non-empty set:")
# Create a non-empty set 'n' with the elements 0, 1, 2, 3, and 4 using a set literal:
n = set([0, 1, 2, 3, 4])
# Print the non-empty set 'n':
print(n)
# Print the data type of 'n', which should be 'set':
print(type(n))
# Print a newline for separation:
print("\nUsing a literal:")
# Create a set 'a' using a set literal with elements 1, 2, 3, 'foo', and 'bar':
a = {1, 2, 3, 'foo', 'bar'}
# Print the data type of 'a', which should be 'set':
print(type(a))
# Print the set 'a':
print(a)
Sample Output:
Create a new set: set() <class 'set'> Create a non empty set: {0, 1, 2, 3, 4} <class 'set'> Using a literal: <class 'set'> {1, 2, 3, 'bar', 'foo'}
For more Practice: Solve these Related Problems:
- Write a Python program to create a set from a list of numbers with duplicates and print the resulting set.
- Write a Python program to create a set from user input where the input is a comma-separated string of values.
- Write a Python program to generate a set containing all prime numbers less than 50 using set comprehension.
- Write a Python program to construct a set from the characters of a given string and display its sorted version.
Python Code Editor:
Previous: Python Sets Exercise Home.
Next: Write a Python program to iteration over sets.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.