How to Use the Python len() Function
In this tutorial, you'll learn how to use the len() function to find the length of an object in Python. This tutorial illustrates examples of how to find the length of a string, dictionary, list, and tuple.
Python len() Syntax
The syntax of the len() function is as follows:
len(object)
Remarks
- object: The object that you want to find its length and can be bytes, tuple, range, list, dictionary, or set.
Example
Find the Length of a String
The following code illustrates an example of how to get the length of a string using the len() function:
# find the length of a string# find the number of characters of a stringstr = "Learn how to develop a web application in Python using Flask"str_length = len(str)print("The length of the string: ", str_length)
Output:
The length of the string: 60
Find the Number of Characters in a Word
The following code illustrates an example of how to find the number of characters in a word:
# find the length of a word# find the number of characters in a wordword = "Programming"numebr_of_character = len(word)print("The number of characters: ", numebr_of_character)
Output:
The number of characters: 11
Find the Length of a List
The following is an example of how to find the number of items in a list:
# find the length of a list# find the number of items of a listbrands = ["Microsoft", "Google", "Apple","Oracle", "Facebook", "Twitter", "IBM"]brands_length = len(brands)print("The length of the list: ", brands_length)
Output:
The length of the list: 7
Find the Length of a Dictionary
The following program find the number of items of a dictionary:
# find the length of a dictionary# find the number of items of a dictionarystudents = {"1001": {"Name": "James","Email": "james@somemain.com"},"1002": {"Name": "Jonh","Email": "jonh@somemain.com"},"1003": {"Name": "Roland","Email": "roland@somemain.com"}}students_length = len(students)print("The number of items of a dictionary: ", students_length)
Output:
The number of items of a dictionary: 3
Find the Length of a Tuple
The following code find the number of items in a tuple:
# find the length of a tuple# find the number of items of a tuplefruits = ("Apple", "Grape", "Orange", "Kiwi", "Melon", "Mango")fruits_length = len(fruits)print("The length of a tuple: ", fruits_length)
Output:
The length of a tuple: 6
In this tutorial, you've learned how to use the len() function in Python. This tutorial illustrated examples of how to find the length of a list, string, dictionary, and tuple.