Get Length of a List in Python Without Using Len()
Last Updated :
29 Jan, 2024
Python len() method is the most common and widely used method for getting the length of a list in Python. But we can use other methods as well for getting the length or size of the list. In this article, we will see how to find the length of a list in Python without using the len() function.
Find The Length Of A List In Python Without Using Len()
Below are some of the ways by which we can find the length of a list in Python without using the len() function in Python:
- Using Loop
- Using a While Loop
- Using Recursion
- Using List Comprehension
Find The Length of a List Using Loop
We can iterate through the list and count the elements using a loop.
Python3
my_list = [ 32 , 4445 , 67 , 78 , "Lokesh" , "Bhopal" ]
count = 0
for _ in my_list:
count + = 1
print ( "The length of the list is : " , count)
|
Output
The length of the list is : 6
Get Length of a List In Python Without Using Len()
Similar to the for loop, we can use a while loop to iterate through the list and count the elements.
Python3
my_list = [ 32 , 4445 , 67 , "demo" , 78 , "Lokesh" , "Bhopal" ]
count = 0
while (my_list):
my_list.pop()
count + = 1
print ( "The length of the list is : " , count)
|
Output
The length of the list is : 7
Find The Length of a List Using Recursion
We can also find the length of list using recursion. In this example, we have used recursion to find the length of a list.
Python3
def list_size(my_list):
if not my_list:
return 0
my_list.pop()
return 1 + list_size(my_list)
my_list = [ 32 , 89.0 , 456 , 23 , 78 , "Lokesh" , "Bhopal" ]
count = list_size(my_list)
print ( "The length of the list is : " , count)
|
Output
The length of the list is : 7
Length of a List Without Using Len() Using List Comprehension
We can use a list comprehension to create a new list with the same elements and then find the length of the new list.
Python3
my_list = [ 1 , 2 , 3 , 4 , 5 ]
length = sum ( 1 for _ in my_list)
print ( "Length of the list:" , length)
|
Output
Length of the list: 5
Share your thoughts in the comments
Please Login to comment...