Tutorial Playlist
In 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 in Python 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.
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.
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.
Here is the syntax of len() function:
len(object)
In the above syntax,
object: The collection or iterable object for which you want to determine the length.
Let us learn how to use the len() function with the help of some examples.
Code:
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!".
Code:
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 my_list contains 5 elements.
Code:
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 my_tuple consists of 5 elements.
Code:
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 my_dict.
In most cases, len() is safe to use with built-in Python data structures, but when working with custom classes or non-iterable objects, you should handle potential exceptions or define the behavior using the __len__() method for custom classes. The len() function typically does not raise exceptions for built-in Python data structures like strings, lists, tuples, and dictionaries.
However, there are some scenarios where len() can raise exceptions:
Example:
class MyCustomClass:
def __init__(self):
self.data = [1, 2, 3]
obj = MyCustomClass()
length = len(obj) # Raises TypeError: object of type 'MyCustomClass' has no len()
Example:
number = 42
length = len(number) # Raises TypeError: object of type 'int' has no len()
Certainly, let's explore the usage of the len() function with various Python data structures, including built-in sequences, collections, other data types, third-party libraries, and user-defined classes, along with advanced code examples.
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
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
number = 42
try:
length = len(number) # Raises TypeError: object of type 'int' has no len()
except TypeError as e:
print(f"Error: {e}")
# Using len() with NumPy arrays
import numpy as np
my_array = np.array([1, 2, 3, 4, 5])
array_length = len(my_array) # Returns 5
# Using len() with Pandas DataFrames
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
df_length = len(df) # Returns 3 (number of rows)
class MyCustomClass:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
my_obj = MyCustomClass([1, 2, 3, 4, 5])
custom_length = len(my_obj) # Returns 5 (custom implementation)
In this example, the MyCustomClass class defines a custom __len__() method, allowing the len() function to work with instances of this class.
Let's explore an advanced len() Python example by creating a program that calculates the length of sequences within a list and then performs customized operations based on those lengths. In this example, we'll use a list of words, and we'll categorize the words into different groups based on their lengths.
Code:
# Define a list of words
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "kiwi", "lemon", "mango"]
# Initialize empty dictionaries to categorize words by length
word_groups = {}
# Calculate the length of each word and categorize them
for word in words:
length = len(word)
# Check if a group for this length exists, create it if not
if length not in word_groups:
word_groups[length] = []
# Append the word to its respective group
word_groups[length].append(word)
# Print the categorized words
for length, group in word_groups.items():
if length == 1:
print(f"Single-letter words: {', '.join(group)}")
else:
print(f"Words with length {length}: {', '.join(group)}")
In this program, we start with a list of words. We use the len() function to calculate the length of each word, and then we categorize the words into dictionaries based on their lengths. The keys in the word_groups dictionary represent word lengths, and the values are lists of words with those lengths.
We iterate through the list of words, and for each word, we calculate its length. If a group for that length does not yet exist in the word_groups dictionary, we create it. We then append the word to its respective group.
Finally, we print the categorized words. If the length is 1, we print them as single-letter words; otherwise, we display words grouped by their lengths.
The len() function in Python offers several advantages when used in programming. These advantages contribute to code clarity, efficiency, and flexibility, making it a valuable tool in various scenarios.
Here are the key advantages of using the len() function:
Example:
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
print(my_list[i])
The len function in Python isn't just about counting characters or list items. It's about efficient code, optimizing operations, and enhancing readability. As we've journeyed through its varied applications and nuances, it's evident that mastering this function is key to solidifying one's Python foundations.
If you're looking to further elevate your Python prowess, consider the advanced courses offered by upGrad, ensuring you stay at the forefront of coding excellence.
The len() function works directly on lists to count items. However, for arrays, especially when using libraries like numPy, dimension specifics are essential.
Iterative methods or specific string properties can be employed for this purpose.
Yes, you can seamlessly integrate len() within user-defined functions for diverse functionalities.
The if len(Python_object) construct in Python checks if the specified object (like a list or string) has a non-zero length, executing the subsequent code block if true.
Typically, len() is efficient. However, for significantly large data structures, alternate optimization techniques might be more suitable.
PAVAN VADAPALLI
popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .