len() Function in Python

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
By Rahul Janghu
Free
star4.90
Enrolled: 1000
Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
Rahul Janghu
Free
4.90
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

The len() function in python takes an object as an argument and returns the length of that object. For example, the len() function can return the number of items in a python list.

Syntax of len() function in Python

The syntax of len() is:

Parameters of len() function in Python

The len() function takes a single argument, which can be:

  • sequence - string, bytes, iterables like tuple, list etc
  • collection - dictionary, set, frozen set etc

Return values of len() function in Python

The len() function returns the number of elements in a sequence or collection object.

Exceptions of len() function in Python

If we do not pass an argument or an invalid one, it will raise a TypeError exception.

A TypeError is raised when the datatype isn't a collection or a sequence. E.g., boolean, int etc.

Code:

Output:

Example of len() function in Python

Let's look at an example in which we will find the number of elements inside the list, i.e., the length of the list.

Code:

Output:

What is len() function in Python?

The len() is a built-in python function that takes an object as an argument and returns the length of that object. For example, it can return the number items in a python list.

Code:

Output:

Whenever we use built-in data types and other third-party types with len(), the len function doesn’t iterate through the data structure. The length of the container object is stored as an attribute of the object. The value of this attribute is modified each time items are added to or removed from the data structure, and len() returns this value of the length attribute. This ensures that len() works efficiently.

How to Use Python's len() Function

Using len() With Built-in Sequences

A sequence is an object containing items in an ordered manner. Lists, tuples, and strings are the basic examples of built-in sequences in python, and the len() function is used to calculate the lengths of these sequences.

Code:

Output:

Explanation:

In the above code snippet, to find the length of the string name, the list food_items, and the tuple having coordinates, we use len() similarly. Therefore, all these three data types are valid arguments for len(). The function len() returns an integer as it counts the number of items in the object that is passed as an argument. The function returns 0 if the argument is an empty sequence.

We can also use range() to create a range object sequence. A range object doesn’t store all the values but generates them when they are needed. However, we can find the length of this range object using len().

Code:

Output:

Explanation:

This range of numbers includes the integers from 1 to 9 (10 is excluded). We can determine a range object's length using the start, stop, and step value arguments.

Using len() function with built-in Collections

Collections in python are container-based data types, namely lists, sets, tuples, and dictionaries. Collections have characteristics based on their declaration and usage in a program. A list is declared in square brackets. It is mutable, stores duplicate values, and can access elements using indexes.

Example 1: Determining the length of collection generated using random functions

To find the number of items in a collection, we first use the random function to create a list of random integers and then use the len() function in python.

Code:

Output:

Explanation:

In the above program, we generated a list of 10 random numbers ranging between 1 and 10 named nums using list comprehension. The output will differ each time the code runs since we generate random numbers. In this case, the set contains 6 unique numbers.

Example 2: Determining the number of items in a Dictionary

Dictionary is a built-in data type often used to store items in the form of a key-value pair. When we use a dictionary as an argument for len(), the function returns the number of items in the dictionary.

Code:

Output:

Explanation:

In the above program, The first output returns that there are three key-value pairs in the food items dictionary. And similar to the case with sequences, len() will return 0 when the argument is either an empty dictionary or an empty set.

Using len() function with other built-in Data-types

Data types that do not store more than one item within them cannot be used as an argument for len().

Code:

Output:

The integer, float, Boolean, and complex types are examples of built-in data types that you can’t use with len(). The function raises a TypeError when an argument of an invalid data type is passed to the len() function.

Using the len() function with Third-Party Libraries

We can also use the len() function on objects from various third-party libraries. In this section, we will look at examples of using len() with data types from two popular third-party libraries, namely NumPy and pandas.

Example 1: Using the len() function with NumPy's ndarray

The NumPy module is used for performing computationally intensive tasks and is the building block for various data types.

Using NumPy function np.array(), we can create an object of type <np.ndarray> using the list, passed as an argument.

Code:

Output

Explanation:

In the above program, we created a one dimensional array of length 6 using np.array function and calculated its type and length using type() and len() respectively.

Example 2: Using the len() function with Pandas DataFrame

A Pandas DataFrame is a two-dimensional data structure with labelled axes (rows and columns). Data inside a Panda DataFrame is aligned in a tabular manner in rows and columns. DataFrames are widely used in machine learning, scientific computing, and many other data-intensive fields.

Code:

Output:

Explanation:

In the above program, the keys of our marks dictionary are strings that represent the names of students. The value of each key is a list storing the marks for three subjects: Maths, Physics, and Chemistry. While creating a DataFrame using this dictionary as an argument in the pd.DataFrame function, we have to also define the index using a list that contains the names of three subjects. The created DataFrame contains three rows and four columns. The len() function returns the number of rows in the DataFrame. Pandas DataFrame has a .shape property, which can be used to see the dimension of a DataFrame, i.e. the number of rows and columns in a tuple.

Using len() function on User-Defined Classes

Python's built-in len() function calls a method named __len__() in our class. These special methods, having double underscores, are known as dunder methods as they have double underscores at the beginning and end of the method names. Implementing this method will allow the len() call to work in the class. If it is not implemented, the call to len() will fail with an AttributeError. Python’s built-in len() function calls its argument’s .__len__() method.

Output:

Explanation:

The above program has a class Order having count as an attribute. We have created a dunder function __len__() that returns the total count of orders passed as an argument. So we created an instance named myOrder and passed the count argument as seven, and when len() was called on myOrder, the value of count was returned.

Conclusion

  • In this article, we learned how to use the len() function in python to determine the number of items in sequences, collections, and other third-party data types.
  • The len() function in python takes an object as an argument and returns the length of that object.
  • Python's len function can be used to obtain the length of
    • built-in types,
    • third party data types (like pandas and numpy),
    • user defined classes (by implementing the __len__() method

See Also: