Explain Codes LogoExplain Codes Logo

How do I get the number of elements in a list (length of a list) in Python?

python
len
performance
iterators
Anton ShumikhinbyAnton Shumikhin·Aug 17, 2024
TLDR

Obtain the count of items in a list using the len() function. Apply it to a list named my_list, and voilà! You get the size.

my_list = ['a', 'b', 'c', 'd', 'e'] print(len(my_list)) # Output: 5

Understanding len(): the Reliable Counter

Underneath Python's hood, the len() function calls your object's __len__ method. The size of the list isn't calculated fresh each time you call len(). Instead, for efficiency, this size is stored and retrieved from ob_size—ensuring the fastness of this operation.

Beyond len(): Other Checks and Tricks

Verifying if a list is vacant

Instead of using len(list) == 0, let Python's treatment of empty collections to False guide you:

if not pythonistas: # pythonistas is our list print('Need more Python lovers here!') # A sad truth

Ensuring a list has a set number of elements

To ensure our list is not overpopulating (or underpopulating):

if len(pythonistas) == ideal_population: print('Perfect! We have just the right number of Python enthusiasts.')

Making a list sophisticated: the SmartList

Ever thought about tracking the length within the list itself? Behold, SmartList class:

class SmartList(list): @property def length(self): return super().__len__() s_list = SmartList(['x', 'y', 'z']) print(s_list.length) # Output: 3

Dealing with iterators and generative sequences

len() is might be picky and only counts items for some party invitees (read: non-iterable types). So, here's how we sneak everyone in:

import itertools, collections def count_em(iterator): _, iterator_copy = itertools.tee(iterator) collections.deque(iterator_copy, maxlen=0) # deque consumes iterator quickly and painlessly return sum(1 for _ in iterator) # Obligatory iterator walk of shame just_a_generator = (x for x in range(100)) # a humble generator of the first 100 natural numbers print(count_em(just_a_generator)) # Output: 100

Diving Deep: Relationship with Time and Memory

len() and Time Complexity

len() is a time traveler who always takes the express lane. Regardless of list size, len() operation is O(1), indicating a constant time complexity. Important to keep in mind for performance-critical applications.

Memory Trade-offs

In scenarios where list length is asked more frequently than 'Can Python do this?', creating a class that keeps the count updated can be beneficial:

class CountList(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._count = len(self) def append(self, object): super().append(object) # Where do you want to go today? self._count += 1 # I'll be back def pop(self, index=-1): # Consider that a divorce item = super().pop(index) self._count -= 1 # Hasta la vista, baby return item @property def count(self): return self._count # I'm sorry, Dave. I'm afraid I can't do that

Getting Crafty with Iterables

Treading on thin ice here! Not every iterable sends an invitation to len(). You can use length_hint from operator for a rough size estimation when len() is not available:

from operator import length_hint print(length_hint(my_iterator))