Find size of a list in Python
In Python, List is a collection data-type which is ordered and changeable. A list can have duplicate entry as well. Here, the task is find the number of entries in a list. See the examples below. Examples:
Input : a = [1, 2, 3, 1, 2, 3] Output : 6 Count the number of entries in the list a. Input : a = [] Output : 0
The idea is to use len() in Python
Python3
# Python program to demonstrate working # of len() a = [] a.append("Hello") a.append("Geeks") a.append("For") a.append("Geeks") print ("The length of list is : ", len (a)) |
The length of list is: 4
Example 2:
Python3
# Python program to demonstrate working # of len() n = len ([ 10 , 20 , 30 ]) print ("The length of list is : ", n) |
The length of list is: 3
How does len() work? len() works in O(1) time as list is an object and has a member to store its size. Below is description of len() from Python docs.
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).
Another approach is use the built-in sum() function in combination with a generator expression. This allows you to find the size of a list by summing the number of elements in the list that meet a certain condition.
For example, to find the size of a list, you can use the following code:
Python3
# list of numbers numbers = [ 1 , 2 , 3 , 1 , 2 , 3 ] # find the size of the list size = sum ( 1 for num in numbers) # print the size of the list print (size) |
6
This will output 6, because the list contains 6 elements.
The time complexity of the approach using the sum() function and a generator expression is O(n), where n is the length of the list. This is because the generator expression must iterate through the entire list to count the elements that meet the specified condition.
The auxiliary space complexity of this approach is O(1), because the generator expression only requires a single variable to store the current element being processed.
How to check if a list is empty in Python
Please Login to comment...