In this article, we share 9 ways to find python list length in 2024, including source code and Big-O performance. Whether you’re new to learning Python or an experienced Pythonista looking to boost your skills, we’ve included 9 ways to evaluate python list length for all levels.
As a top 3 language, Python is the go-to for beginners and experienced pros in data science, web development, and more. And when it comes to Python programming, evaluating python list length is one of the most important skills you can learn.
So if you’re ready, let’s explore 9 ways to find Python list length to add to your Python cheat sheet.
Download Hackr.io's Guide To Finding Python List Length PDF
What Is A Python List?
Let’s quickly segue to remind ourselves about the humble yet powerful Python list.
In the simplest terms, the Python list is a dynamic array that can store any object type, including a mixture of different object types in the same list.
Lists are also a built-in data type, meaning they’re bundled with the Python standard library, allowing us to use them as data structures to organize, store and manage data.
Let’s also take a moment to recap two key properties of the Python list, starting with mutability. This key feature allows us to change the elements in a list.
Next, we have the concept of ordering, which means that list elements are stored in the order they are inserted. This also allows us to access elements via indexing. If you’ve ever taken any Python course, you’ll notice that lists and indexing are used often!
So to recap, the Python list is a versatile and widely used data structure for any type of Python project that allows us to create an ordered collection of mutable and dynamic elements.
And when it comes to the length of a list in Python, this is simply the number of elements within the list. But how do you get the length of a list in Python? Great question, let’s dive into 9 different ways to check the length of a list in Python!
If any of this seems new or you want a more in-depth exploration of the Python list, check out our Python masterclass. In this course, I dive deep into the fundamentals of Python with detailed slides, code examples, and interactive coding walkthroughs.
1. Find Python List Length With len()
Perhaps the simplest and most obvious way to check the length of a list in Python is with the built-in len() function, as shown below. This is one of the most fundamental Python concepts when working with lists.
Simply pass a list as the argument to the len() function to return an integer value representing the number of elements in the list.
This method offers constant time and space complexity, making it favorable in terms of Big-O performance.
'''
Find The Length Of A List With len()
Time Complexity: O(1) | Space Complexity: O(1)
'''
lst = [1, 2, 3, 4, 5]
length = len(lst)
2. Evaluate Length Of A Python List With Naive For Loop
Another common approach to get the length of a list in Python is with a naive approach that uses iteration and a for loop, as shown below.
Simply create a counter variable, traverse over the elements in the list, and increment the counter by +1 for each list element. After exiting the loop, the counter variable will represent the number of elements in the list.
This method offers linear time and constant space complexity, making it less favorable in Big-O than the simpler len() function.
'''
Find The Length Of A List With A For Loop
Time Complexity: O(n) | Space Complexity: O(1)
'''
lst = [1, 2, 3, 4, 5]
count = 0
for _ in lst:
count += 1
3. Find List Length With sum()
In this example, we’ll evaluate the length of a list by using a combination of the built-in sum() function and a generator, as shown below.
This is a slightly more advanced approach, as we use a generator expression to create a sequence of 1s to represent each element within the list.
Note that the sequence of 1s is passed as an argument to the built-in sum() function. This sums the 1s to return an integer representing the number of elements in the list.
Note the underscore placeholder within the generator is a throwaway variable, so feel free to ignore this.
This method offers linear time and constant space complexity, making it equal in performance to the simple traversal via iteration, albeit with more concise code.
'''
Find The Length Of A List With sum()
Time Complexity: O(n) | Space Complexity: O(1)
'''
lst = [1, 2, 3, 4, 5]
length = sum(1 for _ in lst)
4. Find Python List Length With str.count()
For this example, we’ll evaluate Python list length using the built-in string count() method, as shown below.
This interesting approach starts by casting a list variable to a string, which is perfectly fine in Python because it’s dynamically typed. This will result in a string representation of the list elements, each separated by a comma character.
We can then use the count() method to evaluate the number of commas within the string. We’ll also need to increment this value by +1 to represent the number of elements in the list (note that for n elements, there will always be n-1 commas).
This method offers linear time and linear space complexity, making it the least performant approach in terms of Big-O that we’ve covered so far.
'''
Find The Length Of A List With str.count()
Time Complexity: O(n) | Space Complexity: O(n)
'''
lst = [1, 2, 3, 4, 5]
length = str(lst).count(',') + 1
5. Evaluate The Length Of A Python List With length_hint()
In this example, we’ll evaluate the length of a list by using the length_hint() function from the operator module, as shown below.
This is an interesting approach, as the length_hint() function returns an estimate of the number of items in an iterable object without actually iterating over it. In our case, we can pass in a list object as the iterable.
It’s important to be aware that the length_hint() function was designed to give rough estimates, which might be useful when you need to optimize memory usage or quickly estimate resource requirements.
That said, it’s really important to remember that length_hint() only provides estimates. So while it can offer better performance than traversal, there is the potential for inaccuracy which could affect other parts of your program.
These are the subtle details you should know if you’re preparing for a Python certification exam.
Finally, this method offers constant time and constant space complexity, making it equal in performance to the simple len() function.
'''
Find The Length Of A List With length_hint()
Time Complexity: O(1) | Space Complexity: O(1)
'''
from operator import length_hint
lst = [1, 2, 3, 4, 5]
length = length_hint(lst)
6. Find Python List Length With sys.getsizeof()
For this example, we’ll evaluate Python list length using the getsizeof() method from the sys module, as shown below.
This unique approach uses the getsizeof() method to return the size of a list variable in bytes. We then perform integer division with the // operator to divide the total bytes by the size of the first element in the list.
Importantly, this means that we’re relying on the assumption that each element is equal in size, meaning there is the potential for inaccuracy. Also, by using integer division, we ensure the length value is a whole number.
In terms of Big-O, this method offers constant time and constant space complexity, making it another contender for the most performant approach that we’ve covered so far.
'''
Find The Length Of A List With sys.getsizeof()
Time Complexity: O(1) | Space Complexity: O(1)
'''
import sys
lst = [1, 2, 3, 4, 5]
length = sys.getsizeof(lst) // sys.getsizeof(lst[0])
7. Use NumPy To Find The Length Of A List
In this example, we’ll evaluate Python list length using the popular NumPy library and its built-in size() method, as shown below.
This approach is also very simple, as we just import the NumPy module, then pass our list variable as an argument to the size() function.
In terms of Big-O, this method offers constant time and constant space complexity, making it equal in performance to the built-in len() function.
If you’re interested in data science, NumPy is one of the most useful tools you have available. Moreover, the size() method tends to be more efficient than len() for large arrays, as NumPy arrays are implemented in C with optimized memory layouts.
'''
Find The Length Of A List With NumPy
Time Complexity: O(1) | Space Complexity: O(1)
'''
import numpy as np
lst = [1, 2, 3, 4, 5]
length = np.size(lst)
8. Use Pandas To Find The Length Of A Python List
This approach to finding the length of a Python list uses the Pandas library, as shown below.
We simply import Pandas, then pass our list variable as an argument to the Series constructor. We can then use the size attribute for the Series object to return the number of elements in the newly constructed Series, and hence the list.
In terms of Big-O, this approach offers linear time and linear space complexity, making it less performant than other methods we’ve covered so far.
That said, if you’re interested in data science, Pandas is also one of the most useful tools available, so it helps to be familiar with how to evaluate data collection size with Pandas.
'''
Find The Length Of A List With Pandas
Time Complexity: O(n) | Space Complexity: O(n)
'''
import pandas as pd
lst = [1, 2, 3, 4, 5]
length = pd.Series(lst).size
9. Find Python List Length With Recursion
Our final method for evaluating Python list length uses a recursive function, as shown below.
Let’s quickly summarize the general approach if you're unfamiliar with recursion.
To begin, we define a base case that’s used to exit the function. We then design the function to reduce a problem into smaller subproblems by recursively calling itself.
Finally, we can produce a solution when we reach the base case, as this signals an exit, triggering a cascade of function returns up the chain of recursive calls.
Let’s now look at our recursive function. We pass a single list parameter and have a base case that can only be true when the list is empty.
If the list is empty, we return 0. Otherwise, we reduce the problem by shrinking the current list with a slice operation to remove the first element.
We can return a recursive call to the recursive function, but importantly, we pass in the newly reduced list, and we increment by +1.
The recursive process will then continue until the base case is reached, signaling an exit and triggering a cascade of recursive function returns. The end result is an integer value to represent the original list length.
In terms of Big-O, this approach offers linear time and linear space complexity, meaning it is one of the least performant methods we’ve covered.
'''
Find The Length Of A List With Recursion
Time Complexity: O(n) | Space Complexity: O(n)
'''
def list_length(lst):
if not lst:
return 0
return 1 + list_length(lst[1:])
lst = [1, 2, 3, 4, 5]
length = list_length(lst)
Wrapping Up
And there you go, 9 ways to find python list length, including source code examples and Big-O performance for each approach.
Whether you’re just starting out in Python or an experienced coder ready to expand your skills, we’ve included methods to evaluate python list length for all skill levels.
We hope you’ve enjoyed learning about the different ways to find python list length, and if you have any more interesting ways to find the length of a Python list, let us know in the comments!
Are you new to programming and ready to learn Python? Check out:
Our Python Masterclass - Python with Dr. Johns
Frequently Asked Questions
1. Can You Change List Length In Python?
Yes, you can change the length of a list in Python because they are mutable, meaning you can add or remove elements. That said, the Python list does not have a length attribute, but you can use various methods to count the number of list elements, as we’ve shown above.
2. How Do I Fix The Size Of A List In Python?
Python lists are mutable, meaning you cannot fix their length. That said, if you want a list with a fixed length, you could create a custom list class or use the built-in tuple data type, which is essentially an immutable list.
People are also reading: