Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

set
python
length()
communitycreator

How to get the length of a set in Python

Onyejiaku Theophilus Chidalu

Overview

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.

How to determine the length of a set

To determine the length of a set in Python, we use the len() function.

Syntax

len(set)

Parameters

The len() function takes a single mandatory parameter, which is the set data type.

Return value

The len() function returns the length of the set passed to it.

Example

# creating a set
myset = {"USA", "CANADA", "BRAZIL"}

# implementing the len() function
print(len(myset))
Implementing the len() function

Explanation

  • Line 2: We create the set myset.
  • Line 5: We use the 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.

RELATED TAGS

set
python
length()
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring