How do I get the number of elements in a list in Python?

Viewed 3656210

How do I get the number of elements in the list items?

items = ["apple", "orange", "banana"]

# There are 3 items.
12 Answers

You can use the len() function to find the length of an iterable in python.

my_list = [1, 2, 3, 4, 5]
print(len(my_list))  # OUTPUT: 5

The len() function also works with strings:

my_string = "hello"
print(len(my_string))  # OUTPUT: 5

So to conclude, len() works with any sequence or collection (or any sized object that defines __len__).

There is an inbuilt function called len() in python which will help in these conditions.

a=[1,2,3,4,5,6]
print(len(a))     #Here the len() function counts the number of items in the list.

Output:

>>> 6

This will work slightly different in the case of string (below):

a="Hello"
print(len(a)) #Here the len() function counts the alphabets or characters in the list.

Output:

>>> 5

This is because variable (a) is a string and not a list, so it will count the number of characters or alphabets in the string and then print the output.

To get the number of elements in any sequential objects, your goto method in Python is len() eg.

a = range(1000) # range
b = 'abcdefghijklmnopqrstuvwxyz' # string
c = [10, 20, 30] # List
d = (30, 40, 50, 60, 70) # tuple
e = {11, 21, 31, 41} # set

len() method can work on all the above data types because they are iterable i.e You can iterate over them.

all_var = [a, b, c, d, e] # All variables are stored to a list
for var in all_var:
    print(len(var))

A rough estimate of the len() method

def len(iterable, /):
    total = 0
    for i in iterable:
        total += 1
    return total

There are three ways that you can find the length of the elements in the list. I will compare the 3 methods with performance analysis here.

Method 1: Using len()

items = []
items.append("apple")
items.append("orange")
items.append("banana")

print(len(items))

output:

3

Method 2: Using Naive Counter Method

items = []
items.append("apple")
items.append("orange")
items.append("banana")

counter = 0
for i in items:
    counter = counter + 1

print(counter)

output:

3

Method 3: Using length_hint()

items = []
items.append("apple")
items.append("orange")
items.append("banana")

from operator import length_hint
list_len_hint = length_hint(items)
print(list_len_hint)

output:

3

Performance Analysis – Naive vs len() vs length_hint()

Note: In order to compare, I am changing the input list into a large set that can give a good amount of time difference to compare the methods.

items = list(range(100000000))

# Performance Analysis
from operator import length_hint
import time

# Finding length of list
# using loop
# Initializing counter

start_time_naive = time.time()
counter = 0
for i in items:
    # incrementing counter
    counter = counter + 1
end_time_naive = str(time.time() - start_time_naive)

# Finding length of list
# using len()
start_time_len = time.time()
list_len = len(items)
end_time_len = str(time.time() - start_time_len)

# Finding length of list
# using length_hint()
start_time_hint = time.time()
list_len_hint = length_hint(items)
end_time_hint = str(time.time() - start_time_hint)

# Printing Times of each
print("Time taken using naive method is : " + end_time_naive)
print("Time taken using len() is : " + end_time_len)
print("Time taken using length_hint() is : " + end_time_hint)

Output:

Time taken using naive method is : 7.536813735961914
Time taken using len() is : 0.0
Time taken using length_hint() is : 0.0

Conclusion

It can be clearly seen that time taken for naive is very large compared to the other two methods, hence len() & length_hint() is the best choice to use.

In terms of how len() actually works, this is its C implementation:

static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
    Py_ssize_t res;

    res = PyObject_Size(obj);
    if (res < 0) {
        assert(PyErr_Occurred());
        return NULL;
    }
    return PyLong_FromSsize_t(res);
}

Py_ssize_t is the maximum length that the object can have. PyObject_Size() is a function that returns the size of an object. If it cannot determine the size of an object, it returns -1. In that case, this code block will be executed:

    if (res < 0) {
        assert(PyErr_Occurred());
        return NULL;
    }

And an exception is raised as a result. Otherwise, this code block will be executed:

    return PyLong_FromSsize_t(res);

res which is a C integer, is converted into a Python int (which is still called a "Long" in the C code because Python 2 had two types for storing integers) and returned.

How to Find Length of List in Python

List in Python is implemented to store the sequence of various types of data that is ordered and changeable, it can have duplicate values as well. Here, Python has three methods to find the length of list:

  1. len()

It is build-in function called len() for getting the total number of elements in a list. The len() method takes argument where you may provide a list and returns the length of the given list. It is the most convenient ways to find the length of list in Python.

    #Finding length of list by using len() method
    list_example = [1, 2, 3, 4, 5,6,7,8,9]
    print("The length of list is: ", len(list_example))
    The output will be:
    
    Output:
    The length of list is:  9
  1. Naive Method

length of list can be easily found using for loop and this method is called as Naive method. It can be summarized as follows:

Firstly, declare a counter variable and initialize it to zero.

Using for loop,traverse through all the data elements and after encountering every element,increment the counter variable by 1.

Now, the length of the array will be stored in the counter variables and it will represent the number of elements in the list.

#Finding length of list by using Naive method
#Initializing list
list_example = [1, 2, 3, 4, 5,6,7,8,9]
print("The list is: ", str(list_example))
#finding length of list using loop
counter = 0
for i in list_example:
    counter = counter + 1
print ("Length of list using Naive Method is: ", str(counter))
  1. length_hint()

This method is defined in operator class and it can also define the length of list.

#Using Length_hint() Method
from operator import length_hint
list_len_1 = [1, 2, 3, 5, 6, 'PickupBrain']
list_len_hint = length_hint(list_len_1)
print(list_len_hint)

Performance test of len(), Naive Method and lenght_list Methods

This time analysis will help to understand how much time it takes to execute all the methods, which will help you to chose one over another.

#Code for Performance Analysis
from operator import length_hint
import time
#define list
list_example = [1, 2, 3, 4, 5,6,7,8,9]
print("The list is: ", list_example)
# Using Naive method & loop to find length of list
# Initializing counter
start_naive_time = time.time()
counter = 0
for i in list_example:
    counter = counter + 1
    end_naive_time = float(time.time() - start_naive_time)
# Using len() method
start_len_time = time.time()
list_len = len(list_example)
end_len_time = float(time.time()- start_len_time)
# Using length_hint() method
start_hint_time = time.time()
list_hint = length_hint(list_example)
end_hint_time = float(time.time()- start_hint_time)
#Printing time for each method
print("Time taken by Naive Method: ", end_naive_time)
print("Time taken by Length_hint() Method: ", end_len_time)
print("Time taken by len() Method: ", end_hint_time)
The output will be this:

Output:

The list is:  [1, 2, 3, 4, 5, 6, 7, 8, 9]
Time taken by Naive Method:  3.0994415283203125e-06
Time taken by Length_hint() Method:  4.76837158203125e-07
Time taken by len() Method:  1.1920928955078125e-06

Conclusion The time taken is Naive Method >> len() >length_hint()

Related