Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Len() Function in Python

Python is one of the most widely used programming languages in the world, thanks to its simple syntax, versatility, and ease of use. One of the many built-in functions in Python is the len() function. This function is commonly used to calculate the length of an object in Python, including strings, lists, tuples, dictionaries, and sets.

What is Len Function in Python?

The len function in Python is a built-in function that returns the length of an object. It is commonly used to calculate the number of characters in a string, the number of elements in a list or tuple, or the number of key-value pairs in a dictionary.

Here is an example that demonstrates the use of len() function with strings:

# Define a string variable
string_variable = "Hello PrepBytes!"

# Calculate the length of the string using len() function
length_of_string = len(string_variable)

# Print the length of the string
print("Length of string_variable is:", length_of_string)

Output:

Length of string_variable is: 16

Explanation: In the example above, we first defined a string variable string_variable that contains the value "Hello PrepBytes!". We then used the len() function to calculate the length of the string and stored the result in the variable length_of_string. Finally, we printed the value of length_of_string to the console.

In this example, the len() function returns the number of characters in the string string_variable, which is 16. The len() function can be used with other objects as well, such as lists, tuples, and dictionaries, to calculate the number of elements or key-value pairs in the object.

Syntax of Len Function in Python

In Python, the len() function is used to get the length (number of items) of a sequence or a collection such as a string, list, tuple, dictionary, or set.

The syntax for using the len() function is as follows:

len(sequence)

Here, the sequence can be any iterable object (i.e., an object that can be looped over).

Parameters of Len Function in Python

The len function in Python takes a single parameter, which is the sequence or collection for which you want to get the length.

For example, to get the length of a list, you would use the following code:

my_list = [1, 2, 'PrepBytes', 4, 5, False, 7]
list_length = len(my_list)
print(list_length)

Output:

7

Explanation – In this example, the len() function returns the number of items in the my_list variable, which is 7.

Return Value of Len Function in Python

The len function in Python returns an integer value that represents the number of items in the given sequence or collection.

For example, if you call len() on a string, it will return the number of characters in that string. If you call len() on a list, it will return the number of elements in that list.

Examples of Len Function in Python

Here are some examples of using the len function in Python:

Example 1: Find the length of a nested list
Below is the code implementation and explanation of this example

my_list = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]
total_elements = 0
for sublist in my_list:
    total_elements += len(sublist)
print(total_elements)

Output:

10

Explanation: In this example, we have a nested list with different lengths of sublists. To find the total number of elements in the list, we can use a for loop to iterate over each sublist and add the length of each sublist to a running total.

Example 2: Finding the length of a NumPy array
The len() function in Python can also be used with third-party libraries that implement their own sequence or collection data types.

import numpy as pb

my_arr = pb.array([1, 2, 3, 4, 5])
arr_length = len(my_arr)
print(arr_length)

Output:

5

Explanation: In this example, we use the NumPy library to create a NumPy array with five elements. We then call len() on the array, which returns the number of elements in the array (which is 5 in this case).

Example 3: Using len() function on User-Defined Classes
In Python, you can also use the len() function with user-defined classes by defining the len() method for your class. The len() method should return the number of elements or items in the class instance.

class MyList:
    def __init__(self, items):
        self.items = items
    
    def __len__(self):
        return len(self.items)


my_list = MyList([1, 2, 3, 4, 5, 6, 7, 8, 9])
list_length = len(my_list)
print(list_length)

Output:

9

Explanation: In this example, we create a MyList instance with nine items and call the len() function on the instance, which returns the number of items in the instance (which is 9 in this case).

By defining the len() method for your user-defined class, you can make instances of your class behave like sequences or collections in Python, allowing you to use them with built-in functions like len().

Example – 4 Using len() function with built-in Collections
The len() function in Python can be used with various built-in collections to get the number of elements or items in the collection.

from collections import OrderedDict

my_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
dict_length = len(my_dict)
print(dict_length)

Output:

5

Explanation: In this example, we use the OrderedDict() function from the collections module to create an ordered dictionary with five key-value pairs. We then call len() on the dictionary, which returns the number of key-value pairs in the dictionary (which is 5 in this case).

Exceptions of Len Function in Python

Here are some of the exceptions that can be raised when using the len function in Python:

  • TypeError: This exception is raised when the object passed to the len() function is not a sequence or collection data type, or does not support the len() method.
  • AttributeError: This exception is raised when the object passed to the len() function does not have a len() method defined.
  • NotImplementedError: This exception is raised when the len() method is not implemented for a user-defined class that is used with the len() function.
  • OverflowError: This exception is raised when the result of calling len() on an object is too large to be represented by an integer. This can happen with very large lists.
  • MemoryError: This exception is raised when there is not enough memory to complete the len() operation. This can happen when calling len() on a very large object.

It’s important to handle exceptions properly when using the len function in Python to ensure that your code is robust and does not crash unexpectedly.

Summary
Here is a summary of the key points covered in this conversation about using the len function in Python:

  • The len function in Python is used to get the number of elements or items in a sequence, collection, or other data types.
  • The syntax of the len() function is len(S) where S is the sequence, collection, or other data types you want to get the length of.
  • The len() function can be used with built-in sequence and collection data types in Python, such as lists, tuples, sets, and dictionaries.
  • The len() function can be used with third-party libraries that implement their own sequence or collection data types, such as NumPy arrays and Pandas dataframes.
  • We can also use the len() function with user-defined classes in Python by defining the len() method for your class.

FAQs

Here are some frequently asked questions about using the len function in Python:

Q1: What happens if I call the len() function on a non-sequence or non-collection data type in Python?
Ans: If you call the len() function on a non-sequence or non-collection data type in Python, you will get a TypeError indicating that the object does not support the len() function.

Q2: Can I use the len() function to get the number of elements in a nested sequence or collection in Python?
Ans: Yes, you can use the len() function to get the number of elements in a nested sequence or collection in Python by calling len() recursively on each level of the nesting.

Q3: Can I use the len() function to get the size of a file or directory in Python?
Ans: No, the len() function cannot be used to get the size of a file or directory in Python. Instead, you can use the os.path.getsize() function to get the size of a file, or the os.path.getsize() function in combination with the os.walk() function to get the size of a directory.

Q4: Can I use the len() function to get the number of elements in a NumPy array or Pandas dataframe with missing values?
Ans: Yes, you can use the len() function to get the number of elements in a NumPy array or Pandas dataframe with missing values, but the result will include the missing values. If you want to exclude missing values from the count, you can use the numpy.count_nonzero() or pandas.DataFrame.count() function instead.

Leave a Reply

Your email address will not be published. Required fields are marked *