Python len Function

The Python len() function is useful to find the length of an object. Or, say, it returns the total number of items (elements) in an object. If you are finding the string length, then the len() function returns the total number of characters.

In this section, we discuss how to use the Python len() function on strings, tuples, lists, dictionaries, Sets, Bytes, and range to find the length.

Python len() function syntax

The syntax of the len() function is as shown below.

len(Object_Name)

Parameter: Here, the object name can be a string, list, tuple, dictionary, or set whose length must be calculated. Whatever object is passed to the Python len() function, it calculates the length and returns the result.

Return Value: The len() function returns an integer indicating the total number of items in a given object.

Python len() function to find string length

When you use this Python function on a String object, it counts and returns the total number of characters (including spaces) in a string. Or, say, find the length of a string.

The syntax of the string len() function is

len(stringName)

As you can see, the len() function accepts a string as a parameter and returns the total number of characters in it, including white spaces and special characters.

In this example, we declared a string and assigned ‘Tutorial Gateway’ to it. Next, we utilized the len() function to find its length. Here, the Python len() function counts the total number of individual characters in it, including a white space, and returns 16 as the output.

a = 'Tutorial Gateway'
print(len(a))
16

Similarly, If we use the len() function on an empty string, it returns 0 because there are no characters in it.

a = ''
print(len(a))
0

TIP: Please refer to the Program to find the string length article to see the other options.

Python len() function to find list length

A list is the most common data structure, and finding its length is a common scenario. The built-in list len() function also helps you to find the total number of List items. The syntax of the list len() function is

len(listName)

Here, we must pass ”listName” as a parameter to find the total items in a given list. Unlike the strings, the Python len() function finds the total number of individual items in a list. It considers a single entry as one, whether it can be an individual item or a nested list.

To demonstrate the list len() function, we declared an integer list and applied the method on it. As you can see from the result, it returns the total number of items or elements in the given list.

n = [15, 20, 35, 40, 55, 60, 70]
print(len(n))
7

Empty List

If we apply the Python len() function on an empty List to find its length, it returns 0 because there are no elements in it.

n = []
print(len(n))
0

Using the len() function on a string list

Similarly, we used the len() function on a list containing the string elements (words). The len() function calculates the number of elements in a string list without any issue.

a = ['apple', 'mango', 'orange', 'cherry','banana']
print(len(a))
5

Using the Python len() function on a nested list

When it comes to nested lists, people usually confuse the return value. If you observe the example below, we declared a list of lists where there are three sub-lists, each sub-list has two list items. Here, the len() function considers each nested list as one entry and returns 3 as the length.

a = [[1, 2], [3, 4], [5, 6]]
print(len(a))
6

TIP: Please refer to the Program to find the list length article to see the other options.

Python len() function to find the tuple length

Similar to the lists, we can use the len() function on tuples to find the total number of items in them. The syntax of the tuple len() function is

len(tuple)

Here, the len() function considers each item in a tuple as 1. This example calculates the length of a Tuple, which means counting the total number of items in a tuple. First, we declared an integer Tuple and applied the len() function to return the number of items in an integer Tuple.

n = (10, 20, 30, 40, 50, 60, 70, 80, 90)
print(len(n))
9

Similarly, we used the Python len() function in a tuple of string items, where each item is considered a single entity and counts the total number of strings in a tuple.

a = ('Banana', 'Orange', 'Blackberry', 'Apple')
print(len(a))
4

TIP: Please refer to the Program to find the tuple length article to see the other options.

Python len function to find dictionary length

Apart from lists and tuples, we can use the len() function on collections such as dictionaries, sets, or frozen sets. The len() function on the Dictionary returns the length. Or calculates the total number of available items in a given Dictionary. The syntax of the dictionary len() function is

len(dictionayName)

As you can see from the syntax, the Python len() function accepts the dictionary name and returns the total number of key-value pairs (elements) in it.

In the example below, we declare a dictionary with integer keys and fruits as the values. Next, we utilized the len() function to find out the total number of key-value pairs in the dictionary.

a = {1: 'mango', 2: 'kiwi', 3: 'cherry'}
print(len(a))
3

If we use the len() function on an empty dictionary, it will return 0 because there are no key-value pairs to count.

b = dict()
print(len(b))
0

Similarly, we can use the Python len() function on mixed dictionary items. In the example below, we declared a dictionary with string and integer values. Next, the len() function finds the total number of elements (key-value pairs) in the mixed dictionary.

c = {'ID': 42, 'name': 'Kevin', 'age': 25, 1: 1200}
print(len(c))
4

Python len() function to find the set length

The len() function also finds the total number of items in a set or the length. The syntax of the set len() function is

len(setName)

Here, we must pass the set name as the parameter value to find the total number of elements in a given set.

In the example below, we declared a numeric set with seven items. Within the print() statement, we utilized the len() function to find the total number of items in a set.

a = {125, 200, 350, 400, 505, 607, 760}
print(len(a))
7

Similarly, the following example calculates the length of an asset with string items.

s = {'apple', 'mango', 'cherry', 'kiwi', 'orange', 'banana'}
print(len(s))
6

TIP: Please refer to the Program to find the set length article for other options.

Python len() function to find the length of an array

In this example, we find the size of an array. First, we calculate the length of an empty array. Next, find the total items in an Integer and String array.

Arr = []
print(len(Arr))

ArrExample = [5, 12, 35, 22, 40, 5]
print("\n", ArrExample)

print(len(ArrExample))

stringArr = ['apple', 'cherry', 'kiwi', 'mango', 'orange', 'banana']
print("\n", stringArr)

print(len(stringArr))
Python len function to find length

How to find the byte length?

The Python len() function also allows you to find the Byte length, and this example returns the same.

b = b'Simple Example' 
print("Bytes = ", len(b))
Bytes =  14

Python len() function inside a for loop

In all the above examples, we have used the len() function to find the length of a list, tuple, set, string, and dictionary. However, we can use it inside the for loop to iterate over the list items from start to end index position.

In the example below, we declared a list to demonstrate the len() function inside a for loop. However, the process is the same for strings, tuples, etc. Here, the range() function iterates from the starting index position 0 and ends before the value returned by the len() function. If len(n) is 4, it stops at 3 because it is the last index position.

n = [10, 20, 30, 40]

for i in range(len(n)):
    print('Index Position =', i, 'Value =', n[i])

Result

Index Position = 0 Value = 10
Index Position = 1 Value = 20
Index Position = 2 Value = 30
Index Position = 3 Value = 40

The len function is not only about returning object size, but you can also find the range length. In this example, we declare a range from 4 to 10 and return the total number of elements between that range. To better understand, we used another example with a big range.

a = range(4, 10)
print(len(a))

b = range(15, 109)
print(len(b))
6
94

Python len() function on a numpy ndarray

Apart from the regular objects and collections, we can use the len() function on numpy ndarray to find its length. In the example below, we have declared a numpy array and utilized the len() function to find the total number of items in it.

import numpy as np

n = np.array([11, 22, 33 ,44, 55])
print(len(n))
5

Python len() function on pandas dataframe

In the example below, we have declared an employee’s details and converted it to a pandas DataFrame. Next, the len() function finds the total number of items in a pandas dataframe.

import pandas as pd

empDict = {'name': 'Miller', 'Age': 32, 'Job': 'Developer'}
df = pd.DataFrame(empDict.items())
print(df)
print(len(df))
      0          1
0  name     Miller
1   Age         32
2   Job  Developer
3

Python len() function alternatives

In the above section, we used the built-in common len() function to find the length of a list, string, tuple, dictionary, set, numpy array, and a data frame. However, there are alternatives to find the length of an object, such as using loops, enumerate, lambda, list comprehensions, etc.

Using a for loop

As we all know, the for loop is the most common way of iterating over the elements in an object. The for loop is helpful to iterate over lists, tuples, sets, dictionaries, or string characters.

In the following example, we will use a for loop to iterate over the list items and find their length. Here, the for loop iterates the list items from start to end. On each iteration, the length variable is incremented by 1, resulting in the total number of list items.

n = [9, 8, 7, 6, 5, 4]
length = 0

for i in n:
    length += 1
   
print(length)
print(len(n))
6
6

Using a while loop

In the following example, we used a while loop with a try and except block to find the length of an object and handle errors. Here, we defined a custom function and utilized the iter() function.

Within the function, we initialize the counter variable to 0, and it will return the length of a given object. The iter() function converts the given list, string, or any collection to an iterator object, which gives one item at a time.

As our idea is to pull all items in an object one after the other until there are no items, we used the while loop. Here, we have defined an infinite while loop with a True value. So, we must manually stop it inside the block.

The next() function reads the next element from the iterator object, and the count value is increased by 1. Once there are no items in the iterator, the StopIteration exception occurs, and the break statement will exit the loop.

def custom_length(a):
    count = 0
    i = iter(a)
    while True:
        try:
            next(i)
            count += 1
        except StopIteration:
            break
    return count


n = [10, 20, 30, 40]
print(custom_length(n))
4

If you replace the list with a string, it will print the length of the string. Please replace the line below.

n = [10, 20, 30, 40]

With the following line.

n = "hello it"
8

Using list comprehension

If you are comfortable with list comprehensions, other than the Python len() function, it is the most reliable way to find the length of a string, list, or any other object. Here, we used the built-in sum() function to calculate the total number of characters (length) in a given string.

n = "hello world"

total = sum([1 for _ in n])
print(total)
11

Using enumerate()

As we all know, when iterating over any object, the enumerate() function automatically runs the counter value. We don’t have to use a separate variable to store the count value; it can be done using the enumerate() function.

Here, enumerate(n, 1) means on each iteration, the enumerate reads one character (item) from a string and accumulates the counter value. The count variable holds the last index position, and it is the length of the string.

def custom_length(n):
    count = 0
    for count, _ in enumerate(n, 1):
        pass
    return count


a = "hello world!"
print(custom_length(a))
12

Using functools reduce() function

We can use the reduce() function available in the functools module to find the length of an object. However, it is not recommended for use because of its complex nature and the use of lambda expressions. The built-in Python len() function is the better option.

In the example below, we declared an integer list and applied the reduce() function with a lambda expression. Here, on each iteration, the count value increments from index position 0.

from functools import reduce

n = (11, 22, 33, 44, 55)
total = reduce(lambda count, _: count + 1, n, 0)
print(total)
5