How to Get the Number of Elements in a Python List?
In this article, we will discuss how to get the number of elements in a Python List.
Examples:
Input: [1,2,3,4,5]
Output:
No of elements in the list are
5Input: [1.2 ,4.5, 2.2]
Output:
No of elements in the list are
3Input: [“apple”, “banana”, “mangoe”]
Output:
No of elements in the list are
3
Before getting the Number of Elements in the Python List we have to create an empty List. After creating an empty list we have to insert the items or elements into the list. There are two methods to get the number of elements in the list i.e,
- Using Len( ) function
- Using for loop
Using Len() function
We can use the len function i.e len( ) to return the number of elements present in the list
Python3
# Returning the number of elements using # len() function in python list = [] # declare empty list # adding items or elements to the list list .append( 1 ) list .append( 2 ) list .append( 3 ) list .append( 4 ) # printing the list print ( list ) # using the len() which return the number # of elements in the list print ( "No of elements in list are" ) print ( len ( list )) |
[1, 2, 3, 4] No of elements in list are 4
Using for loop
We can declare a counter variable to count the number of elements in the list using a for loop and print the counter after the loop gets terminated.
Python3
# Python Program for returning the number # of elements in the list using for loop list = [] # declaring empty list # inserting elements in the list using # append method list .append( 1 ) list .append( 2 ) list .append( 3 ) list .append( 4 ) # declaring count variable as integer to keep # track of the number of elements in for loop count = 0 # for loop for iterating through each element # in the list for i in list : # increments count variable for each # iteration count = count + 1 # prints the count variable i.e the total number # of elements in the list print ( list ) print ( "No of elements in the list are" ) print (count) |
[1, 2, 3, 4] No of elements in the list are 4
Hence, in this way, we can return the number of elements of a list in python using for loop.