Set Length

 

What You'll Learn: In this tutorial, you'll discover how to find the length of a set in Python. This helps you know how many items are in the set.

Using the len() Built-in Function

To get the length of a set, you can use the len() function. This function returns the number of items in the set.

Example Code:

python
# Create a set with some elements
set_1 = {"apple", "banana", "cherry"}
set_1_length = len(set_1)
print(f"Length of the set: {set_1_length}")

Output: Length of the set: 3

What's Happening Here?

  • len(set_1) returns the number of items in set_1, which is 3.

Finding the Length of an Empty Set

If the set is empty, the length will be zero.

Example Code:

python
# Create an empty set
set_1 = set()
set_1_length = len(set_1)
print(f"Length of the set: {set_1_length}")

Output: Length of the set: 0

What's Happening Here?

  • len(set_1) returns 0 because the set is empty.

Try It Yourself: Fun Exercises

  1. Count Your Favorite Colors:
    • Create a set of your favorite colors.
    • Use the len() function to find out how many colors are in the set.
  2. Measure Your Book Collection:
    • Make a set of book titles you've read.
    • Use the len() function to see how many books are in your collection.

Summary:

In this Python tutorial, we learned how to use the len() function to find the length of a set. This function is helpful for knowing how many items are in your set. Keep experimenting and have fun with sets in Python!