
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get the size of a list in Python?
In Python, a list is an ordered sequence that can hold several object types, such as integers, characters, or floats. In other programming languages, a list is equivalent to an array.
In this article, we need to determine the size of a list, which refers to its length. For instance, the list [10, 20, 30, 40] has a length of 4.
Using 'len()' method
In Python, the len() method returns the number of items in a list.
Example
In the following example, we have created an input list and to find the length of the list, it is passed an argument to the len() method -
my_list = ['Hello', 12,'Tutorialspoint', 3, 24, 9] print("Given list-",my_list) my_len=len(my_list) print("Length of the given list -",my_len)
Following is the output of the above code -
Given list- ['Hello', 12, 'Tutorialspoint', 3, 24, 9] Length of the given list - 6
Using a for loop
We can also find the length of the list by iterating through it using a for loop.
Example
Here, we have initialised the count variable to zero and iterated through the list and incremented each time by 1 -
count=0 my_list = ['Hello', 12,'Tutorialspoint', 3, 24, 9] print("Given list-",my_list) for i in my_list: count=count+1 print("Length of the list-",count)
Following is the output of the above code -
Given list- ['Hello', 12, 'Tutorialspoint', 3, 24, 9] Length of the list- 6
Using __len__() Function
The __len__() function in Python returns a positive integer representing the length of the object on which it is called. It implements the in-built len() function.
Example
The following program returns the size of the list using the __len__() function -
# input list my_list = ['Hello', 12,'Tutorialspoint', 3, 24, 9] # getting list length using the __len__() function my_len = my_list.__len__() # Printing the size of a list print("Size of a List = ", my_len)
Following is the output of the above code -
Size of a List = 6