Home »
Python »
Python Reference »
Python Built-in Functions
Python len() Function: Use, Syntax, and Examples
Python len() function: In this tutorial, we will learn about the len() function in Python with its use, syntax, parameters, returns type, and examples.
By IncludeHelp Last updated : June 23, 2023
Python len() function
The len() function is a library function in Python, it is used to get the length of an object (the object may a string, list, tuple, etc). It accepts an object and returns its length (total number of characters in case of a string, the total number of elements in case of an iterable).
Syntax
The following is the syntax of len() function:
len(object)
Parameter(s):
The following are the parameter(s):
- object – An object like string, list etc whose length to be calculated.
Return Value
The return type of len() function is <class 'int'>, it returns length of the object.
Example 1: Find the length of a string
x = "Hello, world!"
print("Length of", x, "is", len(x))
x = "This a simple program"
print("Length of", x, "is", len(x))
Output
Length of Hello, world! is 13
Length of This a simple program is 21
Example 2: Find the length of a list
x = [10, 20, 30]
print("Length of", x, "is", len(x))
x = [101, "Hell0", 30, 50]
print("Length of", x, "is", len(x))
Output
Length of [10, 20, 30] is 3
Length of [101, 'Hell0', 30, 50] is 4
Example 3: Find the length of a tuple
x = ("New Delhi", "Indore", "Banglore")
print("Length of", x, "is", len(x))
x = ()
print("Length of", x, "is", len(x))
Output
Length of ('New Delhi', 'Indore', 'Banglore') is 3
Length of () is 0
Example 4: Find the length of a dictionary
# Creating dictionary
alphabets = {"a": "apple", "b": "ball", "c": "cat", "d": "dog"}
# Printing the dictionary
print("alphabets:", alphabets)
# Length of the dictionary
print("The total elements are:", len(alphabets))
Output
alphabets: {'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
The total elements are: 4