A set stores multiple items in a single variable.
You can create a set by using curly ({}
) brackets.
The set collection is unordered (Unordered sets have no defined order for their items.) (You cannot refer to set items by index or key because they can appear in a different order every time you use them.).
The set collection is unchangeable (after declaration, you cannot modify the set items).
numbers_set = {
0, 1, 2, 3, 4, 5
}
print(numbers_set)
{0, 1, 2, 3, 4, 5}
In the above example, we declared a set of items from 0
to 5
using a curly bracket ({}
) and printing that set using the print()
function.
There is no restriction on adding the same items to the set more than once, but Python internally removes duplicate items from the set.
numbers_set = {
0, 1, 1, 2, 2, 2
}
print(numbers_set)
{0, 1, 2}
In the above example, we added integers 1
and 2
multiple times to the set, but as a result, we got unique items from the given set.
There is no restriction on adding similar data type items into the set, you can add different data types as well.
set1 = {0, 1, 2}
set2 = {"Red", "Blue", "Green"}
set3 = {True, False, True}
set4 = {2, "Red", True}
print(set1)
print(set2)
print(set3)
print(set4)
{0, 1, 2}
{'Red', 'Blue', 'Green'}
{False, True}
{2, 'Red', True}
In the above example, we created four different sets (set1, set2, set3, and set4
) and added different data types of data into the set.
In the first set, we added integer data type items (set1 = {0, 1, 2}
) in the second set, string data type items (set2 = {"Red", "Blue", "Green"}
) in the third set, boolean data type items
(set3 = {True, False, True}
), and in the fourth set, we added a combination of different data type items (set4 = {2, "Red", True}
).
You can also create a set using the set()
constructor.
numbers_set = set((0, 1, 2, 3, 4, 5))
print(numbers_set)
{0, 1, 2, 3, 4, 5}
In the above example, we use a set()
constructor for creating the set.
To determine how many items are in the set, use the len()
function.
numbers_set = {
0, 1, 2, 3, 4, 5
}
print(len(numbers_set))
6
In the above example, the number of items count is 6.