How to get the size of a list in python?

The size of a list refers to the number of items present in the list. Let us consider a list my_list = [1, "red", 4.8, "apple"]. The size of my_list is 4. There are different methods to find the size of the list. Some of them are discussed as follows.

Calculating the size of the list using len() function

len() is an inbuilt function in python to calculate the number of entries in the list. It takes a sequence(strings, lists, tuples, etc) as a parameter and returns the length of the sequence. The time complexity for len() function is O(1).

Let us consider a list color_list = ["red", "green", "black"]. The color_list is passed as an argument to len() function. len(color_list) gives output as 3.

color_list = ["red", "green", "black"]
print("color_list = ", color_list)
size = len(color_list)
print("size of color_list:", size)

The output for color_list size

color_list =  ['red', 'green', 'black']
size of color_list: 3

Calculating the size of the list using for loop

Let us consider a list color_list = ["red", "green", "black"]. A counter variable is initialized to 0. For loop iterates over the color_list and the counter variable increments by 1 at each iteration. The value of the counter variable gives the length of the list as output.

color_list = ["red", "green", "black"]
print("color_list = ", color_list)
counter = 0
for item in color_list:
    counter += 1
print("size of color_list: ", counter)​

The output for color_list size

color_list =  ['red', 'green', 'black']
size of color_list:  3
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions