A set in Python is used to store multiple unordered and unchangeable items in a single variable.
A set is written with braces ({}
).
For example:
myset = {"USA", "CANADA", "BRAZIL"}
In the code above, the variable myset
represents the set, while "USA"
, "CANADA"
, and "BRAZIL"
are the elements of the set.
To determine the length of a set in Python, we use the len()
function.
len(set)
The len()
function takes a single mandatory parameter, which is the set data type.
The len()
function returns the length of the set passed to it.
# creating a setmyset = {"USA", "CANADA", "BRAZIL"}# implementing the len() functionprint(len(myset))
myset
.len()
function to get the length of the set and print it.Note: The output of the code above,
3
, means that the set contains three elements. It represents the length of the given set.