Python: Find the length of a set
Write a Python program to find the length of a set.
Visal Presentation:
Sample Solution:
Python Code:
# Create a set 'setn' with elements 5, 10, 3, 15, 2, and 20.
setn = {5, 10, 3, 15, 2, 20}
# Print a message to indicate the original set elements.
print("Original set elements:")
# Print the contents of 'setn'.
print(setn)
# Print the type of 'setn'.
print(type(setn))
# Print a message to indicate finding the length of the set.
print("\nLength of the said set:")
# Use the 'len()' function to find and print the length (number of elements) of 'setn'.
print(len(setn))
# Create a set 'setn' with repeated elements, all 5.
setn = {5, 5, 5, 5, 5, 5}
# Print a message to indicate the original set elements.
print("Original set elements:")
# Print the contents of 'setn'.
print(setn)
# Print the type of 'setn'.
print(type(setn))
# Print a message to indicate finding the length of the set.
print("\nLength of the said set:")
# Use the 'len()' function to find and print the length of 'setn', which will be 1 due to duplicates being removed in a set.
print(len(setn))
# Create a set 'setn' with repeated elements, all 5 and an additional element 7.
setn = {5, 5, 5, 5, 5, 5, 7}
# Print a message to indicate the original set elements.
print("Original set elements:")
# Print the contents of 'setn'.
print(setn)
# Print the type of 'setn'.
print(type(setn))
# Print a message to indicate finding the length of the set.
print("\nLength of the said set:")
# Use the 'len()' function to find and print the length of 'setn', which will be 2 due to duplicates being removed and the additional element.
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
Python Code Editor:
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 Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics