How to Get the Number of Elements in a Python List
After reading this article, you will be able to learn how to get the Number of Elements in a Python List. As we know, Python consists of various built-in methods. len() is one of the pre-defined Method which returns the length of given Sequence. The sequence can be a list, a string, a tuple, a set, etc. On the other hands, we can count each character by iterating through the given string.
Find the number of elements in a list in Python
Let’s have a look at using both the methods to get the number of elements in a Python List.
Approach – 1: Using len() Method
As said, len() returns the length of the sequence. So, let’s have a look at its Syntax and its Usage.
Syntax: >>> len(sequence)
Where sequence can be a list, tuple, string, set, etc.
Let’s have a glance over the following code to Count the Number of Elements in a given List.
l=[1,2.3,"hi",'@',1+3j] # a list of various typed objects b=len(l) # b is the length of list l print("Length =",b)
From the above code, given list is [1,2.3, “hi”,’@’,1+3j] which is a collection of the various typed object like Integer, Floating-Point Number, String, Character and a Complex Number. Whereas, b is a variable which holds the length of the list l. So, the output of the above code will be as follows
Length = 5
Since the list l contains 5 elements, len() returned 5. Hence, our Output will be 5. Now, let’s have a look at another approach to counting the number of elements of a given list.
Approach – 2: Straight Forward Method
In this approach, we increment the value of count for each element of the given list. So, we can get the total number of elements in a given list. For this, we use looping statements like for to iterate through the given list. Let’s have a look at following code
l=[1,2.3,"hi",'@',1+3j] count=0 for i in l: count=count+1 print("Length =",count)
Here, the count is initially initialized to ‘0’ to count each character. For each element in the given list, we were incrementing the value of count by 1. So that we can get the total number of elements in a given list.
Output: The output of the above code will be as follows
Length = 5
In this way, we can get the number of elements in the given list.
To know more about the Operations on list Click Here ->Operations on a List