How to Use Len in Python

Python is a dynamic, high-level programming language with a design philosophy that emphasizes code readability. If you’re coding in Python, one built-in function you’ll frequently encounter is len(). This tutorial will show you how to use len in Python, which is used to count the number of elements in objects such as strings, lists, and dictionaries.

Understanding the len() Function

The len() function in Python is used to get the length or size of objects like lists, arrays, dictionaries, strings, etc. It takes one argument, i.e., the object. Here is a simple syntax:

In the above syntax, ‘object’ could be a valid Python object.

Using len() with Strings

Let’s first see how to use the len() function with strings in Python.

The output will be:

18

This is because our string comprises 18 characters including the space.

Using len() with Lists

Besides strings, you can use the len() function to find the length of a list.

The output will be:

5

As there are five elements in the list, so, the length of the list is 5.

Using len() with Dictionary

Similarly, len() works with dictionaries. It will return the number of key-value pairs in the dictionary.

The output will be:

3

There are three key-value pairs in the dictionary, hence the length of the dictionary is 3.

The full code:

Conclusion

The len() function is a simple and useful function in Python that lets you determine the length or size of different objects like strings, lists, and dictionaries. In this tutorial, we covered its usage across these objects. Getting familiar with such built-in functions is crucial for writing efficient code. So keep practicing and explore more out of it.