/  Technology   /  How do I get the number of elements in a list?

How do I get the number of elements in a list?

How do I get the number of elements in a list?

 

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. 

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.

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))

The list has 8 elements in which 5 are unique. 

 

Leave a comment