Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to Get the Number of Elements in a Python List?

How to Get the Number of Elements in a Python List?

In this article, we will discuss how we get the number of elements in a list.

Example:

Input: [1,2,3,4,5]
Output: 5
Explanation: No of elements in the list are 5

Input: [1.2 ,4.5, 2.2]  
Output: 3
Explanation: No of elements in the list are 3 

Input: [“apple”, “banana”, “mangoe”]
Output: 3
Explanation: 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 and store some items into the list.

There are three methods to get the number of elements in the list, i.e.:

Using Len() function to Get the Number of Elements

We can use the len( ) function to return the number of elements present in the list.

Python3




# declare list of items
elem_list = [1, 2, 3, 4]
 
# printing the list
print(elem_list)
 
# using the len() which return the number
# of elements in the list
print("No of elements in list are:", len(elem_list))


Output:

[1, 2, 3, 4]
No of elements in list are: 4

Time Complexity: O(1)
Auxiliary Space: O(1)

Using for loop Get the Number of Elements

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 in Python gets terminated. 

Python3




# declare list of items
item_list = [1, 2, 3, 4]
# declare a counter variable
count = 0
 
# iterate on items using for-loop
# and keep increasing the value of count
for i in item_list:
    # increment the value of count
    count = count+1
 
# print the list elements
print(item_list)
print("No of elements in the list are:", count)


Output:

[1, 2, 3, 4]
No of elements in the list are: 4

Time Complexity: O(n) 
Auxiliary Space: O(1)

Using length_hint Get the Number of Elements in a List

Python3




from operator import length_hint
 
l = [1, 2, 3, 4]
print(length_hint(l))


Output:

4

Time Complexity: O(1) 
Auxiliary Space: O(1)

Using Sum Get the Number of Elements in a List

Python




# declare list of items
elem_list = [1, 2, 3, 4]
 
# printing the list
print(elem_list)
 
# using the sum() which return the number
# of elements in the list
print("No of elements in list are:", sum(1 for i in elem_list))


Output:

4

Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(1)

Using Numpy Library

Note: Install numpy module using command “pip install numpy”

Python3




import numpy as np
   
# declare list of items
elem_list = [1, 2, 3, 4]
   
# printing the list
print(elem_list)
   
# using the numpy library
# to return the number of elements in the list
print("No of elements in list are:", np.size(elem_list))


Output:

[1, 2, 3, 4]
No of elements in list are: 4

Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(1)

RELATED ARTICLES

Most Popular

Recent Comments