n this tutorial, we will deep-dive into the len function in Python, a versatile built-in utility. Essential for both beginners and seasoned developers, the len function is instrumental in determining the size of various data structures, whether it's a simple string, a list, or more complex types. Let's unravel its functionalities and best practices.

Overview

The len function in Python stands out as a fundamental tool for measuring the length or size of multiple data types. Its applications span across strings, lists, tuples, and even dictionaries, marking its importance in day-to-day coding tasks and larger-scale projects.

Ready to challenge yourself? Take our Free Python Quiz!

What is Len() function in Python?

The len() function in Python is used to quickly determine the length or the number of items in a collection, such as a string, list, tuple, dictionary, or any other iterable object. It returns an integer representing the length of the given object. The len() function allows developers to make informed decisions and perform appropriate operations based on the size of the collections.


Syntax of Len() function in Python

Here is the syntax of the len() function:

len(object)

Parameters:

  • object: The collection or iterable object for which you want to determine the length.

How do we use the Len() function?

Let us learn how to use the len() function with the help of some examples.

Example 1: Using len() with Strings

text = "Hello, World!"
length = len(text)
print(length)  # Output: 13

In this example, len(text) returns 13, as there are 13 characters in the string "Hello, World!".

Example 2: Using len() with Lists

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)  # Output: 5

Here, len(my_list) returns 5, indicating that the list contains 5 elements.

Example 3: Using len() with Tuples

my_tuple = (10, 20, 30, 40, 50)
length = len(my_tuple)
print(length)  # Output: 5

Similarly, len(my_tuple) returns 5, signifying that the tuple consists of 5 elements.

Example 4: Using len() with Dictionaries

my_dict = {'a': 1, 'b': 2, 'c': 3}
length = len(my_dict)
print(length)  # Output: 3

In this case, len(my_dict) returns 3, which corresponds to the number of key-value pairs in the dictionary.

Exceptions of Len() function in Python

In most cases, len() is safe to use with built-in Python data structures, but there are scenarios where it can raise exceptions:

Custom objects

If you define your own custom classes, you can override the __len__() method to specify how the len() function behaves for instances of your class. If the __len__() method is not defined, calling len() on an instance of that class will raise a TypeError.

class MyCustomClass:
    def __init__(self):
        self.data = [1, 2, 3]

obj = MyCustomClass()
length = len(obj)  # Raises TypeError: object of type 'MyCustomClass' has no len()

Non-Iterable objects

The len() function is meant for iterable objects. Using it on non-iterable objects like integers or floats raises a TypeError.

number = 42
length = len(number)  # Raises TypeError: object of type 'int' has no len()

Examples of Len() Function in Python

Built-in sequences (Lists, Tuples, Strings)

my_list = [1, 2, 3, 4, 5]
list_length = len(my_list)  # Returns 5

my_tuple = (10, 20, 30, 40, 50)
tuple_length = len(my_tuple)  # Returns 5

text = "Hello, World!"
string_length = len(text)  # Returns 13

Built-in collections (Dictionaries, Sets)

my_dict = {'a': 1, 'b': 2, 'c': 3}
dict_length = len(my_dict)  # Returns 3

my_set = {10, 20, 30, 40, 50}
set_length = len(my_set)  # Returns 5

Using len() with third-party libraries

import numpy as np
import pandas as pd

my_array = np.array([1, 2, 3, 4, 5])
array_length = len(my_array)  # Returns 5

data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
df_length = len(df)  # Returns 3 (number of rows)

Advanced example

words = ["apple", "banana", "cherry", "date", "elderberry"]
word_groups = {}

for word in words:
    length = len(word)
    if length not in word_groups:
        word_groups[length] = []
    word_groups[length].append(word)

for length, group in word_groups.items():
    print(f"Words with length {length}: {', '.join(group)}")

Advantages of using the Len() Function

  • Determine Length: Quickly calculate the size of data structures.

  • Readability: Improves code clarity.

  • Looping and Conditions: Helps in iterations and conditional logic.

  • Versatility: Works with various built-in types, third-party libraries, and custom classes.

  • Error Handling: Validate input sizes effectively.

Conclusion

The len function in Python isn't just about counting elements. It’s a robust tool that enhances code clarity, enables efficient data handling, and provides versatility across various use cases. Whether working with built-in types, libraries, or custom classes, the len function is a cornerstone of Python programming.

Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source

Article link:http://pybeginners.com/article/len-function-in-python/