- how to get the size of a list in python
- List in Python
- list size
- Example 1:
- Example 2:
- Length of List
- len() function
- For Loop
- Related Posts:
- Python List Length or Size: 5 Ways to Get Length of List
- Python List Length using the len() function
- Python List Length using a for-loop
- Check if a Python list is empty or not empty
- Get Length of Python List of Lists
- Get Length of Each List in a Python List of Lists
- Conclusion
how to get the size of a list in python
This article is about how to get the size of a list in Python and the number of elements present in the list i.e. length of the list.
List in Python
There are different data types in Python that are capable of storing sequences of items. One of them is a list. It can be defined as an ordered collection of items that can be of different data types. In this article, we are going to learn different methods to find the size and length of a list using Python.
The length and size are two different terms. The length of a list is determined by the count of data elements inside that list. On the other hand, the size of a list is basically the number of bytes occupied in memory by the list object.
list size
One of the most essential requirements in computer programs is memory management. When writing large codes, it is necessary to make sure there is much available memory space so that new processes can be added to it. To handle memory efficiently, we need to know how much memory is required by the objects and data structures used in the code. For this, we need to determine the size of the list.
Python has a sys module that provides the getsizeof() function. The function accepts an object and calls __sizeof()__ method which returns the number of bytes currently being used by the data structure along with the garbage collector overhead if the object is managed by the garbage collector. That is why the size of the list obtained using getsizeof() function is greater than the size acquired through __sizeof()__ method. The garbage collector is used to keep track of all the objects in the memory.
Example 1:
# Using Sys Module to getsizeof() import sys # Create and initialize list list1 = [1, 2, 3, 4, 5] list2 = [1, "Programming", "Entechin", 5.3] # Print the sizes of lists print ("Size of list 1 in bytes: ", sys.getsizeof(list1)) print ("Size of list 2 in bytes: ", sys.getsizeof(list2)) .
In this example, we have first created two lists as shown in the code. List1 contains 5 integers and list2 is composed of mixed datatypes. In order to determine the size of the list, we have passed the list object to the getsizeof() function which on execution return the sizes of list1 and list2 in bytes along with garbage collector overhead. List1 and list2 are occupying 112 bytes and 104 bytes in the memory.
You can also use of __sizeof_() method directly to find the size of the object. The size returned by this method is only of the object that is why it is smaller than the size determined by the getsizeof() because the latter takes overhead into account.
Example 2:
Let’s take the same example 1 but this time determine the size of the list using __sizeof__() method.
# Using __sizeof__() method. import sys # Create and initialize list list1 = [1, 2, 3, 4, 5] list2 = [1, "Programming", "Entechin", 5.3] # Print the sizes of lists print ("Size of list 1 in bytes: ", list1.__sizeof__()) print ("Size of list 2 in bytes: ", list2.__sizeof__()) .
Length of List
In most applications, you are required to perform the same operation on all the elements of a list or to find a certain item. So for all such applications, we need to iterate or traverse over the list. For this, you need the total length of the list.
len() function
The python has a built-in function len() to measure the length of a list. It takes the list as an argument and returns the total number of elements in the list. It is considered to be one of the best methods to find the length of a list as it returns the length in O(1) time.
# Using len() Function list = ['apple', 'mango', 'orange', 'guava'] length = len(list) print ("Length of a list: ",length) .
For Loop
For loop can also be used to calculate list length. It goes throughout the list and counts every single element in the list. After initializing a list, declare a counter variable and initialize it to zero. using for loop, traverse through the list one by one on each iteration and increment the counter variable by 1. After the last iteration, the counter will hold the length of the list.
# Using For Loop # Create and Initialize a list1 list1 = [ "John", "Harry", "Peter"] # Declare a variable to store the length of list count = 0; for i in list1: count = count + 1 print("Length of list is: ", count) .
As the length is analogous to the count of list elements that’s why the value in the count variable represents the length of the list. The for loop can also be used along with other functions to iterate over the list which is discussed in the previous article.
Python is the most popular programming language. Size and length are often misunderstood by each other but these are two different terms. In this tutorial, we have learned the different ways to obtain the size and length of lists. If you want to learn about Python, please follow our website. Let us know if you have queries regarding this topic or if you want to use cover a certain topic. It would be highly appreciated.
For any questions related to the Size of the list in Python, feel free to Contact Us.
Related Posts:
Python List Length or Size: 5 Ways to Get Length of List
In this tutorial, you’ll learn how to use Python to get the length of a list (or, rather, its size). Knowing how to work with lists is an important skill for anyone using Python. Being able to get a Python list length, is particularly helpful. You’ll learn how to get the Python list length using both the built-in len() function, a naive implementation for-loop method, how to check if a list is empty, and how to check the length of lists of lists.
The Quick Answer: Use len() to get the Python list length
Python List Length using the len() function
The easiest (and most Pythonic) way to use Python to get the length or size of a list is to use the built-in len() function. The function takes an iterable object as its only parameter and returns its length.
Let’s see how simple this can really be:
# Get the length of a Python list a_list = [1,2,3,'datagy!'] print(len(a_list)) # Returns: 4
We can see here that by using the len() function, we can easily return the length of a Python list.
In the next section you’ll learn how to use a for-loop naive implementation to get the size of a Python list.
Python List Length using a for-loop
While this approach is not recommended (definitely use the method above!), this for-loop method does allow us to understand an algorithm in terms of counting items in an iterable.
In order to do this, we iterate over each item in the list and add to a counter. Let’s see how we can accomplish this in Python:
# Get the length of a Python list a_list = [1,2,3,'datagy!'] length = 0 for _ in a_list: length += 1 print(length) # Returns 4
This approach certainly isn’t as straightforward as using the built-in len() function, but it does explain some algorithmic thinking around counting items in Python.
In the next section, you’ll learn how to easily check if a Python list is empty or not empty.
Want to learn more about Python for-loops? Check out my in-depth tutorial on Python for loops to learn all you need to know!
Check if a Python list is empty or not empty
In your programming journey, you’ll often encounter situations where you need to determine if a Python list is empty or not empty.
Now that you know how to get the length of a Python list, you can simply evaluate whether or not the length of a list is equal to zero or not:
# How to check if a Python list is empty a_list = [] if len(a_list) != 0: print("Not empty!") else: print("Empty!") # Returns: Empty!
But Python makes it actually much easier to check whether a list is empty or not. Because the value of 0 actually evaluates to False , and any other value evaluates to True , we can simply write the following:
# An easier way to check if a list is empty a_list = [] if a_list: print("Not empty!") else: print("Empty!") # Returns: Empty!
This is much cleaner in terms of writing and reading your code.
In the next section, you’ll learn how to get the length of Python lists of lists.
Learn to split a Python list into different-sized chunks, including how to turn them into sublists of their own, using this easy-to-follow tutorial.
Get Length of Python List of Lists
Working with Python lists of lists makes getting their length a little more complicated.
To better explain this, let’s take a look at an immediate example:
# Get the length of a list of lists a_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] print(len(a_list_of_lists)) # Returns: 3
We can see here, that the code (correctly) returns 3 . But what if we wanted to get the length of the all the items contained in the outer list?
In order to accomplish this, we can sum up the lengths of each individual list by way of using a Python list comprehension and the sum function.
Let’s see how this can be done:
# Get the length of a list of lists a_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] length = sum([len(sub_list) for sub_list in a_list_of_lists]) print(length) # Returns: 9
Finally, let’s see how we can use Python to get the length of each list in a list of lists.
Want to learn more about Python list comprehensions? This in-depth tutorial will teach you all you need to know. More of a visual learner? A follow-along video is also included!
Get Length of Each List in a Python List of Lists
In the example above, you learned how to get the length of all the items in a Python list of lists. In this section, you’ll learn how to return a list that contains the lengths of each sublist in a list of lists.
We can do this, again, by way of a Python list comprehension. What we’ll do, is iterate over each sublist and determine its length. A keen eye will notice it’s the same method we applied above, simply without the sum() function as a prefix.
Let’s take a look at how to do this:
# Get the length of each sublist in a list of lists a_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] lengths = [len(sublist) for sublist in a_list_of_lists] print(lengths) # Returns [3, 3, 3]
In this section, you learned how to use Python to get the length of each sublist in a list of lists.
Want to learn how to append items to a list? This tutorial will teach your four different ways to add items to your Python lists.
Conclusion
In this post, you learned how to use Python to calculate the length of a list. You also learned how to check if a Python list is empty or not. Finally, you learned how to calculate the length of a list of lists, as well as how to calculate the length of each list contained within a list of lists.
To learn more about the Python len() function, check out the official documentation here.