Python: Create a new empty set
Python sets: Exercise-1 with Solution
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'}
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/sets/python-sets-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics