How to get the length of a list in Python

Key takeaways:

  • len() is the most efficient and widely used method to find the length of a list in Python.

  • sum() with a generator is a Pythonic and memory-efficient way to count items in a list.

  • enumerate() in a loop helps count the length while also providing both the index and value of elements in the list.

  • Manual iteration using a for loop helps understand how iteration works but is less efficient than built-in methods.

  • length_hint() gives an estimate of the length, though it may not always be accurate or available for all objects.

  • __len__() is a special method that can be used for length calculation but is generally not recommended for clarity; len() is preferred.

  • reduce() from the functools module can accumulate the length by iterating over the list and counting items.

  • numpy can be used for finding the length of numeric lists using the np.size() function.

  • iter() and next() provide a way to manually iterate through the list and count elements.

  • sum() and map() can be used together by mapping each item to 1 and summing the results to find the length.

In Python, lists are one of the most commonly used data structures. They store multiple items in an ordered, mutable, and indexed collection. At some point, we’ll often need to know how many elements are in a list such as counting items in a shopping list, checking the number of tasks in a to-do list, or finding the number of students in a class roster.

Ways to get the length of a Python list

Python provides several ways to calculate the length of a list, each with different use cases and advantages. We'll explore multiple methods to find the length of a list in Python, ranging from the most straightforward approach to more complex solutions:

  1. len()

  2. for loop

  3. sum() with a generator

  4. enumerate() in a loop

  5. length_hint function

  6. __len__() special function

  7. Using reduce()

  8. Using numpy

  9. Using iter and next

  10. Using sum and map

Method 1: Using the len() function

The easiest and most efficient way to find the length of a list in Python is by using the built-in len() function. It is optimized and directly returns the number of elements in the list.

High level diagram of len() function
High level diagram of len() function

Example

Shown below is an example of how we can use this function.

basic_list = [1, 2, 3, 4, 5]
length = len(basic_list)
print(length)

Method 2: Manually counting elements

While the len() function is quick and convenient, we can also manually count the number of elements in a list by iterating over it. This method is less efficient but might help understand how iteration works.

Example

Shown below is an example of how we can achieve this.

# Initialize a list of numbers
baisc_list = [1, 2, 3, 4, 5]
# Initialize variable to keep count of length
length = 0
# Using a for loop to iterate over each item in the list
for item in baisc_list:
# Increment the length variable for each item
length += 1
# Print the calculated length of the list
print(length)

Start coding with confidence! "Learn Python 3 from Scratch" takes you through Python fundamentals and program structures, culminating in a practical project to solidify your skills.

Method 3: Using sum() with a generator expression

A more Pythonic way to count items in a list involves using a generator expression with the sum() function. This method is elegant and efficient, as it processes the list lazily.

Note: A generator expression is a concise way to create a generator object in Python. It is similar to a list comprehension but instead of returning a list, it returns a generator, which produces items one at a time and is more memory efficient. A generator expression uses parentheses () instead of square brackets [] as used in list comprehensions. Syntax: (expression for item in iterable if condition).

Example

Here's how we can do this.

# Initialize a list of numbers
basic_list = [1, 2, 3, 4, 5]
# Calculate the length of the list using the sum function to count elements
length = sum(1 for _ in basic_list) # Sum up 1 for each element in the list
# Print the calculated length of the list
print(length)

Explanation

Let's go over the code and see what's going on:

  • Line 2: Here, we create the list we're supposed to iterate over.

  • Line 5: Inside this generator expression:

    • (1 for _ in basic_list) can be read as "1 for every element in basic_list". This helps us understand that the generator expression returns 1 for every element it finds inside the list.

    • The sum() function then sums all the 1s returned by the expression and stores the result in length.

  • Line 8: We finally print the result.

Method 4: Using enumerate() in a loop

We can also calculate the length of a list by iterating through its elements using a for loop with enumerate.

Example

Here's how we can use the enumerate function.

# Initialize a list of numbers
basic_list = [1, 2, 3, 4, 5]
# Variable to store the length of the list
length = 0
# Iterate over the list using enumerate to access both index and value
for index, value in enumerate(basic_list):
# Update the length based on the current index (index + 1 gives the count)
length = index + 1
# Print the calculated length of the list
print(length)

Method 5: Using the length_hint() function

In Python, the length_hint() function is a special method that gives an estimate of the number of items in an iterable, though it’s not always exact and may not be available on all objects. It is used primarily for optimization by certain types of iterators.

Example

Here's how we can use the length_hint() function.

#Import length_hint
from operator import length_hint
basic_list = [1, 2, 3, 4, 5]
# Check the length hint (if available)
length = length_hint(basic_list)
print(length) # Output: 5 (This is an estimate of the length)

Method 6: Using __len__() special function

Python lists already have the __len__() method implemented

It is generally not the recommended way to get the length of a list. Instead, the built-in len() function should be used for clarity and readability. However, the __len__() method is indeed available for all built-in collection types like lists.

Example

Show below is an example that demonstrates how we can use this function.

basic_list = [1, 2, 3, 4, 5]
length = basic_list.__len__()
print(length) # Output: 5 (This is an estimate of the length)

Method 7: Using reduce()

The reduce function from the functools module can be used to accumulate the length by iterating through the list and increasing a counter.

Example

Shown below is a detailed example.

from functools import reduce
# List
basic_list = [1, 2, 3, 4, 5]
# Using reduce to find length
length = reduce(lambda count, _: count + 1, basic_list, 0)
print(length) # Output: 5

Explanation

Let's go over the code and try to understand what's going on:

  • Line 1: We're importing the reduce function that we'll use in the code.

  • Line 4: Here, we're defining the list we’re supposed to iterate over and find the length of.

  • Line 7: The reduce function takes three arguments:

    • First is a lambda function:

      • count represents the accumulator that we'll use to keep track of the length.

      • _ represents each element. This is ignore and is not used.

      • count + 1 adds one to the accumulator for each element.

    • The second is the iterable, which is basic_list in this case.

    • The third is the initial value, which in this case is 0.

  • Line 9: When the function finishes executing, we print the length.

Method 8: Using numpy

If you're working with numeric lists, you can use numpy.size() to find the length of a list.

Example

Here's how we can use the numpy.size()method.

import numpy as np
# List
basic_list = [1, 2, 3, 4, 5]
# Using numpy to find length
length = np.size(basic_list)
print(length) # Output: 5

Method 9: Using iter and next

You can find the length of a list using iter() and next() by iterating through the list and counting elements manually.

Example

# List
basic_list = [1, 2, 3, 4, 5]
# Using iter and next to find length
iterator = iter(basic_list)
length = 0
try:
while True:
next(iterator)
length += 1
except StopIteration:
pass
print(length) # Output: 5

Method 10: Using sum and map

You can use sum along with map to count the elements in a list. By mapping each element to 1 and then summing them, you can find the length.

Example

Here's how this combination can be used to get the length of a list.

# List
basic_list = [1, 2, 3, 4, 5]
# Using sum and map to find length
length = sum(map(lambda _: 1, basic_list))
print(length) # Output: 5

Explanation

Here's what's happening in the code:

  • Line 2: Here's the list that we'll be iterating over.

  • Line 5: Here's how this line computes the length:

    • The map function applies a lambda function to each element of basic_list.

    • The lambda function ignores the element (_) and returns 1 for each item.

    • Finally, the sum function sums up all the returned 1s.

  • Line 7: Lastly, we print the calculated length.

Become a Python developer with our comprehensive learning path!

Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.

Conclusion

In Python, finding the length of a list is a simple task, and you have several ways to approach it. The most efficient and widely used method is the len() function, but there are many other methods available, depending on the situation.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What does the capitalize() method do?

The capitalize() method in Python is a string method that returns a copy of the string with its first character converted to uppercase and the rest of the characters converted to lowercase.


What does range() do in Python?

In Python, range() method is a built-in function that generates a sequence of numbers, commonly used for looping a specific number of times in for loops. It produces an iterable object that can be specified with a starting point, an ending point, and an optional step size.


What is length() in Python?

Python does not have a built-in length() function. Instead, it uses the len() function to get the length of objects such as strings, lists, and dictionaries.


What is a length check in Python?

A length check in Python refers to verifying the size or number of elements in an object (like a string, list, or dictionary) using the len() function. For example:

# Length check for a string
text = "Hello"
if len(text) > 5:
    print("The string is longer than 5 characters.")
else:
    print("The string is 5 characters or less.")

What is the size function in Python?

Python does not have a built-in size function. However, specific libraries like NumPy provide a size function to determine the total number of elements in an array.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.size(arr))  # Output: 6

For general Python objects like strings or lists, you can use the len() function instead.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved