Lists in Python are one of the most commonly used built-in data structures. Many times we need to find the length of a list in Python code. Today, we will see all the important methods to find the length of a list in Python.
1. len()
myList = [1, 2, 3, 4, 5]
listLength = len(myList)
print(listLength)
Output:
5
len() method is the easiest way to find the length of any list.
2. Using __len__()
This is similar to len(). len() internally call __len__().
myList = [1, 2, 3, 4, 5]
listLength = myList.__len__()
print(listLength)
Output:
5
3. Using loop
We can use a loop(for loop or while loop) with a counter.
myList = [1, 2, 3, 4, 5]
listLength = 0
for i in myList:
listLength = listLength + 1
print(listLength)
Output:
5
All the above methods are commonly known and are available on most websites but now I am going to present you with some magical methods to find the length of any list in Python. You will not find these methods anywhere on the internet before 07-12-2022, there are two reasons for that, these are not good methods as these are lengthy and contains many operations due to which they are slow and the second reason may be that no one knows/writes before we write these methods.
4. Using dict
myList = [1, 2, 3, 4, 5, 6, 7]
listLength = dict(map(reversed, enumerate(myList)))[myList[-1]] + 1
print(listLength)
Output:
7
5. Using enumerate()
myList = [1, 2, 3, 4, 5, 6, 7]
listLength = max((index for index, item in enumerate(myList) if item == myList[-1]), default=None) + 1
print(listLength)
Output:
7
6. Using Recursion
myList = [1, 2, 3, 4, 5, 6, 7]
listLength = 0
def calc_len(myList):
global listLength
if myList:
listLength += 1
myList.pop()
return calc_len(myList)
return listLength
calc_len(myList)
print(listLength)
Output:
7
Bookmark this page before you lost it because these are very important methods and you will not find these methods anywhere. These methods will help you in many ways.