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:
1 |
len(object) |
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.
1 2 3 |
str = 'Python Programming' str_length = len(str) print(str_length) |
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.
1 2 3 |
list = [1, 2, 3, 4, 5] list_length = len(list) print(list_length) |
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.
1 2 3 |
dict = {'one': 1, 'two': 2, 'three': 3} dict_length = len(dict) print(dict_length) |
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:
1 2 3 4 5 6 7 8 9 10 11 |
str = 'Python Programming' str_length = len(str) print("String Length: ", str_length) list = [1, 2, 3, 4, 5] list_length = len(list) print("List Length: ", list_length) dict = {'one': 1, 'two': 2, 'three': 3} dict_length = len(dict) print("Dictionary Length: ", dict_length) |
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.