how to get the cardinality of a set in python

To get the cardinality of a set in Python, you can use the built-in len() function. Since sets in Python only contain unique elements, the cardinality of a set is simply the number of elements in the set.

Here's an example:

main.py
my_set = {1, 2, 3, 4, 4, 4, 5}  # set with duplicate numbers and unique numbers
cardinality = len(my_set)
print(cardinality)  # output: 5
138 chars
4 lines

In this example, my_set contains elements {1, 2, 3, 4, 4, 4, 5}. However, since sets only contain unique elements, Python will consider my_set to be {1, 2, 3, 4, 5}. The len() function is then used to determine the cardinality of the set, which in this case is 5.

related categories

gistlibby LogSnag