How to use the len() function in Python

Published on Aug. 22, 2023, 12:16 p.m.

To use the len() function in Python, you simply pass an object as an argument, and len() will return the number of items in that object. Here are some examples:

Getting the length of a string:

s = "Hello, world!"
length = len(s)
print(length)  # output: 13

Getting the length of a list:

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)  # output: 5

Getting the length of a dictionary:

my_dict = {"a": 1, "b": 2, "c": 3}
length = len(my_dict)
print(length)  # output: 3

Note that the len() function only works with objects that have a defined length, such as strings, lists, and dictionaries, among others. If you try to use len() with an object that doesn’t have a defined length, you’ll get a TypeError exception.

Tags:

related content