Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Set


Set

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).

Example
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.


A Set Did Not Allow Duplicate Items

There is no restriction on adding the same items to the set more than once, but Python internally removes duplicate items from the set.

Example
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.


Python Set Items Data Types

There is no restriction on adding similar data type items into the set, you can add different data types as well.

Example
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}).


Python set() Constructor

You can also create a set using the set() constructor.

Example
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.


Set Items Count

To determine how many items are in the set, use the len() function.

Example
numbers_set = {
    0, 1, 2, 3, 4, 5
}
print(len(numbers_set))
6

In the above example, the number of items count is 6.