/  Technology   /  How to get the number of elements in a list in Python?
How to get the number of elements in a list in Python

How to get the number of elements in a list in Python?

 

We often fall in need to know the number of elements in any sequence while iterating through it. In this article, let’s discuss all the ways using which we can get the count of elements in a given list. 

 

Using len():

This is the built-in list method which returns the length of a list without bothering about the type of elements present in it. 

 

Example:

list = ['Python', 'i', 2, 25, 'Tutorials', 57]

number_of_elements = len(list)

print("Number of elelments present in the list: ", number_of_elements)

Output:

 

Using for loop: 

Here we don’t use any built-in method. We just defined a method named number_of_elements  which takes in the list. We declare a variable count and set it to 0 and this keeps incrementing upon encountering an element in the list when iterated by an iterator, here element, when put in a for loop.

 

Example:

list = ['Python', 'i', 2, 25, 'Tutorials', 57]

def number_of_elements(list):
   count = 0
   for element in list:
      count +=1
   return count

print("Number of elelments present in the list: ", number_of_elements(list))

Output:

 

Using set():

This method counts all the unique elements in a list i.e. without counting the duplicates. This method returns a set object which removes all the duplicates. We pass this method to the len() list method as:

len(set(sample_list))

 

Example:

list = ['Python', 'i', 2, 25, 'Tutorials', 57]

number_of_elements = len(list)
number_of_unique elements = len(set(list))

print("Number of elelments present in the list: ", number_of_elements)
print("Number of unique present in the list: ", number_of_unique_elements)

Output;

The list has 8 elements in which 5 are unique. 

 

Leave a comment