Home ยป Ways to find length of list in python

Ways to find length of list in python

Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription
Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course

In this example we will get a length of a list in python

Example 1

In this Python list length example, we declare an empty one. We then use the len function to calculate the length of the list.

Next, we declare a list of integers and then we use the len function to calculate the length of the list.

emptyList = []
print(len(emptyList))

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(myList)
print(len(myList))

You will see the following

>>> %Run lengthlist.py
0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
9

Example 2

This example shows the total number of string items or the total number of words in the string List.

myList = ['This', 'is', 'a', 'string', 'list']
print(myList)
      
print( len(myList))

You will see the following

>>> %Run lengthlist1.py
['This', 'is', 'a', 'string', 'list']
5

Example 3

This example uses length_hint()

from operator import length_hint
 
# Initializing list
myList = ['This', 'is', 'a', 'string', 'list']
 
# Printing test_list
print ("The list is : " + str(myList))
 
# Finding length of list using len()
listlength = len(myList)
 
# Finding length of list using length_hint()
listlengthhint = length_hint(myList)
 
# Printing length of list
print ("Length of list using len() is : " + str(listlength))
print ("Length of list using length_hint() is : " + str(listlengthhint))

You will see the following

>>> %Run lengthlist2.py
The list is : ['This', 'is', 'a', 'string', 'list']
Length of list using len() is : 5
Length of list using length_hint() is : 5

Link

This is in our github repository

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More