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
# 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))
|
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.
# 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)
|
Hence, in this way, we can return the number of elements of a list in python using for loop.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Python List count()
In this tutorial, we will learn about the Python List count() method with the help of examples.
The count() method returns the number of times the specified element appears in the list.
Example
# create a list numbers = [2, 3, 5, 2, 11, 2, 7]Explanation
Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.
Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called ob_size, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.
But if you're checking if list size is zero or not, don't use len - instead, put the list in a boolean context - it treated as False if empty, True otherwise.
len(s)
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
len is implemented with __len__, from the data model docs:
object.__len__(self)
Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __nonzero__() [in Python 2 or __bool__() in Python 3] method and whose __len__() method returns zero is considered to be false in a Boolean context.
And we can also see that __len__ is a method of lists:
items.__len__()returns 3.
Get the number of items of a list in Python
In Python, the built-in function len() is used to get the length (the number of items) of a list.
- Built-in Functions - len() — Python 3.9.7 documentation
This article describes the following contents.
- Get the number of items in a list with len()
- For two-dimensional lists (lists of lists)
- For multidimensional lists
See the following article for the usage of len() for objects of other types.
- How to use len() in Python
You can get the total number of elements with len(). If you want to get the number of occurrences of an element, use the count() method or Counter of the standard library collections.
- Count elements from a list with collections.Counter in Python
List in Python
A list in Python is implemented to store the sequence of various types of data. However, there are six data types in Python that are capable of storing the sequences but the most common and reliable type is a list. To learn more about python you can join our Master Python programming course.
A list is defined as a collection of values or items of different types. The items in the list are separated with a comma (,) and enclosed with the square brackets [].
It is defined as follows:
list1 = ['edureka', 'python', 2019]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];If you want to learn Artificial Intelligence and Machine Learning in-depth, come to us and sign up for this Post Graduate Diploma AI and ML courses.
Python List len() Method
Python List Count With Examples
Python Lists can contain objects of the same type or of different types. For example, a List can contain all items as Integer or items as integer, String, boolean etc.
The length of the list can be identified using the len() and using for loop.
Using Len() Function
In Python, you can find the length of the list using the len() function.
Use the below snippet to get the count of elements in list.
Snippet
list = ['a','b','c'] len(list)There are 3 elements in the list. You’ll see the output as 3.
Output
3You’ve calculated the items in the list which have the same type of values. Next, you’ll see the list with different types of items.
Count List with Different Type of Items
The example list contains one character, one number, one boolean value, and one value None which is used to denote the missing data.
However, when a list has None, it is also counted as one element while using len() function.
Snippet
list = ['a',1, True, None] len(list)The example list has 4 values including None. Hence, you’ll see the output 4.
Output
4This is how you can get the number of elements in the list using the len() function. This is also known as finding list length.
Next, you’ll learn how to use for loop.
Using For Loop
In this section, you’ll learn how to count the number of elements in a list using the for loop.
for loop is used to iterate over a sequence of values.
To get the number of elements in the list, you’ll iterate over the list and increment the counter variable during each iteration. Once the iteration is over, you’ll return the count variable which has the total number of elements in the list.
In the below example,
- You’ve initialized a list with different types of values
- Created a function which will iterate the list and count the elements
- Printed the count using print statement.
Snippet
list = ['a',1, True, None] def get_no_of_elements(list): count = 0 for element in list: count += 1 return count print("Number of elements in the list: ", get_no_of_elements(list))There are 4 elements in the list including the None value. Hence you’ll see output 4.
Output
Number of elements in the list: 4This is how you can get the number of elements in a list using for loop.
Next, let us discuss the counting with condition.
Count elements in a flat list
Suppose we have a list i.e.
To count the elements in this list, we have different ways. Let’s explore them,
Use len() function to get the size of a list
Python provides a inbuilt function to get the size of a sequence i.e.
Arguments:
- s : A sequence like object like, list, string, bytes, tuple etc.
It returns the length of object i.e. count of elements in the object.
Now let’s use this len() function to get the size of a list i.e.
Output:
Number of elements in list : 9
How does len() function works ?
When len(s) function is called, it internally calls the __len__() function of the passed object s. Default sequential containers like list, tuple & string has implementation of __len__() function, that returns the count of elements in that sequence.
So, in our case we passed the list object to the len() function. Which internally called the __len__() of the list object, to fetch the count of elements in list.
Use list.__len__() to count elements in a list
We can directly call the __len__() member function of list to get the size of list i.e.
Output:
Number of elements in list : 9
Although we got the size of list using __len__() function. It is not a recommended way, we should always prefer len() to get the size of list.