
Python’s len() Function
The `len()` function in Python is a built-in function that is used to find the length of a sequence, collection, or any other iterable object. It returns the number of items in an object. In this tutorial, you’ll learn how to use the `len()` function with built-in data types, third-party data types, and user-defined classes.
Using len() with Built-in Data Types
You can use the len() function to find the length of built-in data types such as lists, tuples, strings, dictionaries, and sets.
# Finding the length of a list
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(len(my_list)) # Output: 11
# Finding the length of a string
my_string = "Hello, World!"
print(len(my_string)) # Output: 13Using len() with Third-Party Data Types
The len() function can also be used with third-party data types such as NumPy arrays and Pandas series.
import numpy as np
import pandas as pd
# Finding the length of a NumPy array
my_array = np.array([1, 2, 3, 4, 5])
print(len(my_array)) # Output: 5
# Finding the length of a Pandas series
my_series = pd.Series([10, 20, 30, 40, 50])
print(len(my_series)) # Output: 5Providing Support for len() with User-Defined Classes
You can provide support for the len() function with user-defined classes by implementing the __len__() method.
class CustomList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
custom_list = CustomList([7, 8, 9, 10])
print(len(custom_list)) # Output: 4In this example, the CustomList class supports the len() function by defining the __len__() method, which returns the length of the list of items.
Conclusion
The len() function is a versatile tool in Python for finding the length of various data structures. It can be used with built-in data types, third-party data types, and user-defined classes, making it a powerful and flexible function in Python.
