View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

len() Function in Python

Updated on 22/01/20258,501 Views

The len() function in Python is a built-in function for determining the length of an object such as a string, list, or tuple. It returns the number of items in the object.

Often, when working with lists or strings, you may need to determine how many elements or characters they contain. Without a straightforward way to find this, your code can get complicated and less efficient.

Thankfully, the len() function is here to make it easy! With just one line of code, you can find the length of any iterable object.

By the end of this guide, you'll know exactly how to use len() python examples in different situations. This will help you write cleaner, more effective Python code.

Let’s get started!

"Boost your Python skills with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey today!"

What is len() Function in Python?

Whether you're working with a string, list, tuple, or even a dictionary, the len() function helps you quickly find how many items are inside. It’s a handy tool for keeping track of the size of data structures in your code.

For example, if you're working with a list of items, you might need to know how many elements are in the list. Instead of manually counting them, you can simply use the len() function to return the total count.

This makes your code more efficient and easier to maintain.

Syntax of len() Function in Python

len(object)

If you're enjoying learning about Python and ready to dive deeper into software development, consider exploring our Online Software Development Courses. It can help you further enhance your knowledge and take your coding skills to the next level!

Examples of len() Function in Python

The len() function in Python list is extremely versatile and can be used with various data structures, including lists, tuples, and dictionaries.

Using len() with List, Tuple, Dictionary

Let's start with a list. A list is an ordered collection of elements, and the len() function in python list can be used to count how many items are in it.

For example, suppose you have a list of students in a class:

students = ["Anil", "Sam", "Priya", "Yash"]
#get the length of the list
num_students = len(students)
print(num_students)

Output:

4

Explanation:

  • We defined a list called students containing four names.
  • len(students) will return the number of elements in the list, which is 4.
  • The output will be 4, indicating that there are four students.

Now let’s look at a tuple. A tuple is similar to a list but is immutable, meaning its contents cannot be changed after creation.

Here's an example with a tuple of numbers:

numbers = (10, 20, 30, 40, 50)
#get the length of the tuple
num_numbers = len(numbers)
print(num_numbers)

Output:

5

Explanation:

  • We created tuple numbers with five elements.
  • The len() function counts how many items are in the tuple, which is 5.
  • The output will be 5.

Finally, let's explore how len() works with a dictionary. A dictionary is a collection of key-value pairs. In this case, len() will return the number of key-value pairs in the dictionary.

person = {"name": "Parth", "age": 45, "city": "Gurgaon"}
#get the length of the dictionary
num_keys = len(person)
print(num_keys)

Output:

3

Explanation:

  • The dictionary person has three key-value pairs.
  • len(person) counts these pairs and returns 3.
  • The output will be 3.

Also Read: List vs Tuple: Understanding the Differences in Python

How len() Works for Custom Objects?

You can also use len() with custom objects by defining the special method __len__() in your class. This method should return an integer value representing the size or length of the object.

Let’s create a custom class and implement __len__().

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages
    def __len__(self):
        return self.pages  #return the number of pages as the length of the book
#create a Book object
my_book = Book("Python Programming", 350)
#use len() on the custom object
book_length = len(my_book)
print(book_length)

Output:

350

Explanation:

  • We created a class Book with an __init__ method to set the title and number of pages.
  • The __len__() method is defined to return the number of pages in the book as its length.
  • When we call len(my_book), it uses the __len__() method, returning 350.

This is a great example of how the len() function can be applied to custom objects. It can be really useful when you want to give your objects a sense of "size" or "length" and make them compatible with Python's In-built functions like len().

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

What Happens When len() is Called on Empty Objects?

When you use the len() function on an empty object, the result is always 0. This is because an empty object doesn’t contain any elements for the len() function to count.

Here’s how the len() function behaves when called on an empty list:

#create an empty list
empty_list = []
#call len() on the empty list
list_length = len(empty_list)
print(list_length)  #this will print 0

Output:

0

Explanation:

  • We created an empty list called empty_list using square brackets [].
  • When len(empty_list) is called, it checks the number of elements in the list. Since the list is empty, it returns 0.
  • The output of the print() function confirms this by displaying 0.

Now, let’s try modifying the list by adding a few items to understand how len() dynamically updates the count:

#add elements to the list
empty_list.append("Python")
empty_list.append("Tutorial")
list_length = len(empty_list)
print(list_length)  #this will print 2

Output:

2

Explanation:

  • Initially, the list was empty, so len(empty_list) returned 0.
  • After appending two elements, the length of the list changed to 2.
  • When len(empty_list) was called again, it correctly counted the two elements and returned 2.

For example, before processing data, you might want to confirm that a list or dictionary contains elements. Using len() is an efficient way to do this.

This behavior remains consistent with all iterable objects, making len() a reliable tool for such checks.

Python len() in for Loop

Using the len() function in a Python for loop allows you to iterate through a collection and perform operations on its elements based on its length. This approach is useful when you need to access elements using their index or dynamically control loop iterations.

Let’s break this down with an example:

#define a list of programming languages
languages = ["Python", "Java", "C++", "JavaScript"]
#use len() in a for loop to iterate based on index
for i in range(len(languages)):
    #access and print each element using its index
    print(f"Language at index {i}: {languages[i]}")

Output:

mathematica
Language at index 0: Python
Language at index 1: Java
Language at index 2: C++
Language at index 3: JavaScript

Explanation:

  1. Defining the list: We created a list called languages containing the names of programming languages.
  2. Using len() with range(): The len() function calculates the number of items in the list (in this case, 4). The range() function generates indices from 0 to len(languages) - 1.
  3. Iterating with indices: The loop iterates through these indices, allowing access to each element of the list using its index.
  4. Printing the output: Inside the loop, we print the current index and the corresponding element.

Combining len() and Conditional Statements

Let’s take it a step further. Suppose you want to find and print the names of programming languages that have more than 4 characters:

#use len() in a loop with a condition
for i in range(len(languages)):
    if len(languages[i]) > 4:  #check the length of each language name
        print(f"{languages[i]} has more than 4 characters.")

Output:

Python has more than 4 characters.JavaScript has more than 4 characters.

Explanation:

  1. Length check: Inside the loop, len(languages[i]) calculates the length of each string in the list.
  2. Conditional logic: The if condition checks if the length of the current string is greater than 4.
  3. Printing results: If the condition is true, it prints the language name.

This len() python example showcases how the function enhances the utility of a for loop, especially when working with collections like lists.

Also Read: Conditional Statements in Python: If, If else, Elif, Nested if Statements

Exceptions of len() Function in Python

Let’s explore these scenarios and see how to handle them effectively.

1. Calling len() on Non-Iterable Objects

The len() function works only with iterable objects such as lists, strings, tuples, and dictionaries. Using it on a non-iterable object, such as an integer, will raise a TypeError.

Example:

#trying to use len() on an integer
number = 12345
try:
    print(len(number))  #this will raise an error
except TypeError as e:
    print(f"Error: {e}")

Output:

Error: object of type 'int' has no len()

2. Using len() on Custom Objects Without len Method

The len() function requires custom objects to implement the __len__() method. If the method is not defined, a TypeError is raised.

Example:

#custom class without __len__ method
class MyClass:
    pass
my_object = MyClass()
try:
    print(len(my_object))  #this will raise an error
except TypeError as e:
    print(f"Error: {e}")

Output:

Error: object of type 'MyClass' has no len()

3. len() Function on Uninitialized Variables

Calling len() on a variable that has not been initialized results in a NameError.

Example:

try:
    print(len(uninitialized_variable))  #variable is not defined
except NameError as e:
    print(f"Error: {e}")

Output:

Error: name 'uninitialized_variable' is not defined

4. Using len() on Generators or Iterators

The len() function does not work directly on generators or iterators in Python because they don’t store elements in memory.

Example:

#generator expression
generator = (x for x in range(10))
try:
    print(len(generator))  #this will raise an error
except TypeError as e:
    print(f"Error: {e}")

Output:

Error: object of type 'generator' has no len()

Keep practicing different functions and methods in Python, and you'll gradually build confidence and mastery over the language.

FAQ's

1. What is the purpose of the len() function in Python?

The len() function in Python determines the total number of elements in an iterable, such as a list, string, tuple, or dictionary. It’s a versatile tool often demonstrated through len() Python example.

2. Can len() handle nested lists in Python?

Yes, but len() only counts the top-level elements in a nested list. It doesn't dive into the inner lists unless specified through additional logic. For example, len() function in Python list will count nested lists as single elements.

3. How does len() behave when applied to strings?

When used on a string, len() returns the number of characters in the string, including spaces and special characters. This makes it ideal for len() Python example with text data.

4. Can you use len() on sets in Python?

Absolutely! The len() function can count the number of unique elements in a set, making it helpful when working with collections of distinct items.

5. Does len() work with generator objects in Python?

No, len() cannot directly determine the size of generator objects since they are iterators and don’t store their elements in memory.

6. Can len() be overridden for custom objects in Python?

Yes, you can override len() by defining a __len__() method in your class. This allows custom objects to return specific sizes when len() Python example are explored with user-defined classes.

7. Is len() a method or a function in Python?

The len() function is a built-in function, not a method. Unlike methods, it operates independently of the object on which it's called.

8. How does len() behave differently for dictionaries?

When used on dictionaries, len() returns the count of key-value pairs. It’s a common use case in len() Python example for working with key-based data.

9. Can you pass multiple arguments to len()?

No, len() only takes one argument. Passing more than one argument will raise a TypeError.

10. Is len() applicable for empty collections in Python?

Yes, the len() function works seamlessly with empty collections, returning 0. This makes it useful in len() Python example that handle edge cases.

11. Are there alternatives to len() for determining sizes?

While len() is the most straightforward way, you can also use libraries like NumPy for advanced size calculations, especially for arrays and multi-dimensional data.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.