How to find the length of a list
Posted in Python by Dirk - last update: Feb 06, 2024
Using the len() function
The easiest way to find the length of a list in Python is using the built-in len() function. The len()
function returns the number of items in an object: len(my_list)
returns the lenght of my_list
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)
While the len()
function is the most commonly used and recommended method, there are alternative approaches that can be useful in certain scenarios.
Using count variable with a Loop
This approach manually iterates through the list using a loop and increments a counter variable for each element, effectively counting the number of elements in the list.
my_list = [1, 2, 3, 4, 5]
count = 0
for _ in my_list:
count += 1
print(count)
Using enumerate with a Loop
Similar to the previous method, this approach uses enumerate()
to iterate through the list, but it also provides the index along with the element. The count is incremented for each iteration.
my_list = [1, 2, 3, 4, 5]
count = 0
for _ in enumerate(my_list):
count += 1
print(count)
Using range with len()
This method uses the range()
function to generate a sequence of indices based on the length of the list. len(range(len(my_list)))
effectively gives the length of the list.
my_list = [1, 2, 3, 4, 5]
length = len(range(len(my_list)))
print(length)
Using sum and List Comprehension
This method uses a list comprehension to create a list of ones, where each one represents an element in the original list. The sum()
function then adds up these ones, giving the length of the list.
my_list = [1, 2, 3, 4, 5]
length = sum(1 for _ in my_list)
print(length)
Other articles