How to Use the Python len() Function

09/17/2021

Contents

In this article, you will learn how to use the Python len() function.

Python len() Function

The len() function is a built-in function in Python that returns the length of an object. The object can be a string, list, tuple, set, dictionary, or any other iterable object.

Here’s how to use the len() function in Python:

To get the length of a string:
string = "Hello, World!"
print(len(string))  # Output: 13
To get the length of a list:
my_list = [1, 2, 3, 4, 5]
print(len(my_list))  # Output: 5
To get the length of a tuple:
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))  # Output: 5
To get the length of a set:
my_set = {1, 2, 3, 4, 5}
print(len(my_set))  # Output: 5
To get the length of a dictionary (number of key-value pairs):
my_dict = {"apple": 2, "banana": 3, "cherry": 1}
print(len(my_dict))  # Output: 3

In summary, len() is a very useful function in Python that allows you to quickly find the length of an object.