w3resource

Python: Find the length of a set

Python sets: Exercise-15 with Solution

Write a Python program to find the length of a set.

Sample Solution:

Python Code:

#Create a set
setn = {5, 10, 3, 15, 2, 20}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))

setn = {5, 5, 5, 5, 5, 5}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))

setn = {5, 5, 5, 5, 5, 5, 7}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))

Sample Output:

Original set elements:
{2, 3, 5, 10, 15, 20}
<class 'set'>

Length of the said set:
6
Original set elements:
{5}
<class 'set'>

Length of the said set:
1
Original set elements:
{5, 7}
<class 'set'>

Length of the said set:
2

Pictorial Presentation:

Python Sets: Find the length of a set.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find maximum and the minimum value in a set.
Next: Write a Python program to check if a given value is present in a set or not.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Combining Lists Using Zip:

  • Takes multiple collections and returns a new collection.
  • The new collection contains items where each item contains one element from each input collection.
  • It allows us to transverse multiple collections at the same time.
name = 'abcdef'
suffix = [1,2,3,4,5,6]
zip(name, suffix)
--> returns (a,1),(b,2),(c,3),(d,4),(e,5),(f,6)