How to Get the Number of Elements in a Python List?

To get the number of elements in a Python list, use the len(list) function. You don’t need to import any external library because len() is a Python built-in function. You can use it to get the number of elements of several built-in and library types in Python such as tuples and sets.

Here’s the minimal example:

>>> len([2,4,6])
3

Try it yourself on our interactive Python shell:

If you’re a Python nut, you can check out the official docs:

But, I’ll give you the most important information about Python list len() next. Let’s dive into some additional details that may be of interest to you.

Specifications

Just use the len() method intuitively on any object you believe it could work. In the vast majority of cases, it will just work.

Have a look at the formal specification if you want to understand things thoroughly.

Specification: len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Official Docs

You can see that the length function is highly flexible. It’s implemented for many different data types in Python. In fact, each time you implement your own object, you can define the __len__ method to enable the len() function on your custom object as well. Naturally, the __len__ method has been implemented by practically all data types in the Python packages where it makes sense.

Specification: object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

Official Docs

You can define any positive integer return value you want. For collection types such as lists, the return value is the number of elements in the collection. Interestingly, the method also defines whether the default Boolean interpretation of the object should be True (for a positive length >0) or False (for a zero length == 0).

For example, consider the code if o: print('hi') for object o. If the length function len(o) returns 0, the if condition won’t hold (assuming there’s no implementation of the __bool__() method).

Let’s explore a very important question if you’re a serious developer:

What’s the Runtime Complexity of Python List len()?

The runtime complexity of the len() function on your Python list is O(1). It takes constant runtime no matter how many elements are in the list. Why? Because the list object maintains an integer counter that increases and decreases as you add and remove list elements. Looking up the value of this counter takes constant time.

Python List Runtime Complexity Constant O(1)

Python list objects keep track of their own length. When you call the function len(...) on a list object, here’s what happens (roughly):

  • The Python virtual machine looks up the len(...) function in a dictionary to find the associated implementation.
  • You pass a list object as an argument to the len() function so the Python virtual machine checks the __len__ method of the list object.
  • The method is implemented in C++ and it’s just a counter that’s increased each time you add an element to the list and decreased if you remove an element from the list. For example, say, the variable length stores the current length of the list. The method then returns the value self.length.
  • Done.

Here’s a snippet of the C++ implementation of the list data structure:

static int
list_resize(PyListObject *self, Py_ssize_t newsize)
{
    PyObject **items;
    size_t new_allocated, num_allocated_bytes;
    Py_ssize_t allocated = self->allocated;

    // some implementation details

    Py_SET_SIZE(self, newsize);
    self->allocated = new_allocated;
    return 0;
}

Related articles:

Python List Length Limit

What’s the maximal length of a Python list?

The maximal length of a Python list depends on your machine, the memory limit (RAM) and your address space. A lazy upper bound is the maximal integer value on your machine:

>>> import sys
>>> sys.maxsize
9223372036854775807

But, as I said earlier, this is a very lazy upper bound. Multiply this number with four bytes (the size of an integer) and you’ll get 36.893.488.147 GB—hardly a reasonable “upper bound”.

A more practical approach would be to add elements to a Python list until it throws an error. Then, use the len() function to check how many elements are in the list:

>>> lst = []
>>> while True:
	lst.append(1)

	
Traceback (most recent call last):
  File "<pyshell#3>", line 2, in <module>
    lst.append(1)
KeyboardInterrupt
>>> len(lst)
1007494743
>>> 

I aborted this after Python created a list of more than one billion elements.

Python List Length For Loop

You can use the len() function to create a for loop over the indices of a list.

cars = ['audi', 'mercedes', 'bmw', 'vw', 'porsche']
for i in range(len(cars)):
    print(i, cars[i])

'''
0 audi
1 mercedes
2 bmw
3 vw
4 porsche
'''

The range() function requires at least one argument that defines the boundary of the indices (e.g., to iterate over all values in 0, 1, 2, ..., len(cars)).

Python List Length While Loop

You can do the same with a while loop:

cars = ['audi', 'mercedes', 'bmw', 'vw', 'porsche']
i = 0
while i<len(cars):
    print(i, cars[i])
    i += 1

'''
0 audi
1 mercedes
2 bmw
3 vw
4 porsche
'''

The index variable i takes on all indices from 0 to len(cars)—the latter excluded.

Python List Length Initialize

How to initialize a list with n (dummy) elements?

To initialize a list with n elements, use list concatenation [None]*n. See the following example:

lst = [None] * 10
print(lst)
# [None, None, None, None, None, None, None, None, None, None]

However, I have yet to see a case where this makes sense. Usually, it’s much better to create an empty list and add the elements dynamically that you really need.

Python Trim List to Length

To trim a list to a given length, simply use slicing with the notation list[start:stop]. Say, you want to get the first n elements of a list, you can use the notation list[:n] to carve out a slice of the first n elements from the original list.

customers = ['Ann', 'Alice', 'Bob', 'Anne', 'Alice']

print(customers[:3])
# ['Ann', 'Alice', 'Bob']

print(customers[:4])
# ['Ann', 'Alice', 'Bob', 'Anne']

Python Make Lists Equal Length

You can use slicing to make two lists equal-sized. For example, if you want to create two lists with n elements, you can use list_1[:n] and list_2[:n]. But you must make sure that n is smaller or equal the minimum number of elements in any of the lists via n = min(len(customers), len(earnings)).

Here’s the code:

customers = ['Ann', 'Alice', 'Bob', 'Anne', 'Alice']
earnings = [9999, 1345, 22222, 11231, 111, 1999, 1111]
n = min(len(customers), len(earnings))

list_1 = customers[:n]
list_2 = earnings[:n]

print(list_1)
# ['Ann', 'Alice', 'Bob', 'Anne', 'Alice']

print(list_2)
# [9999, 1345, 22222, 11231, 111]

Python List Slice Length

Say, you obtain a slice from a list: now, you can check the length of this slice with the len() function as well.

customers = ['Ann', 'Alice', 'Bob', 'Anne', 'Alice']

slice_1 = customers[2:5]
print(len(slice_1))
# 3

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!