Can you LEN a list in Python?

So, in this tutorial, we are going to discuss what we mean by the length of a list in Python, as well as how we can calculate it using various methods.

We know, Python List is a mutable as well as ordered sequence. It may contain heterogeneous items as well as homogenous ones. It is a vastly used data structure in Python. For traversal as well as for performing some other operations on a list, we sometimes need to find the length of the list.

How to Calculate the length of a List?

Calculating the length or size of a list is analogous to finding the total number of items present in the same.

For example, if we have a list, list1:

The length of the list lis1 is 6. As the total number of elements or items is ‘6’.

Methods of Finding the Length of a List in Python

The length of a list can be calculated in Python by applying various techniques. Below we are going to discuss them one-by-one in detail.

1. Using the len[] method in Python

The built-in len[] method in Python is widely used to calculate the length of any sequential data type. It calculates the number of elements or items in an object and returns the same as the length of the object.

So, we can directly get the length of a list, through passing the same into the built-in len[] method. Let us see how.

#given list l=[11,22,33,44,55,66] #printing the length using len[] print["The length of the list",l, "is :",len[l]]

Output:

The length of the list [11, 22, 33, 44, 55, 66] is : 6

In this code:

  • We firstly take a list, list1
  • Then we directly pass the list into the len[] method and it returns the length of the list. This in our case is 6.

2. Custom Function to Calculate the Length of a List

Now let us define our own function in Python which will calculate the length of a list passed to it and return it where the function was called.

Below is the calc_len[] function that we define to find the length of a list.

def calc_len[l]: c=0 for i in l: c=c+1 return c #given list list1=['A',1,'B',2,'C',3,'D',4] #printing the length using calc_len[] print["The length of the list",list1, "is :",calc_len[list1]]

Output:

calc_len[] Output

Here,

  • In the code above, we define a function calc_len[] which takes the list whose length is to be found as a parameter
  • Inside the calc_len[] function, we initialize a counter c which is increased by 1 on each for loop iteration and stores the total number of items in the list, and finally return the counter c
  • Hence, we pass the list, list1 to our user-defined function
  • cal_len[] which returns us back the length of the list that we print directly.

Conclusion

So, in this tutorial, we learned how we can calculate or find the length of a list in Python. For any questions feel free to use the comment box below.

References

Output: 3

Find the length of List with Python for loop

In order to find the length of the list in Python, using for loop is considered as a traditional technique or a naive method in the following manner:

  • Declare a counter variable and initialize it to zero.
  • Using a for loop, traverse through all the data elements and after encountering every element, increment the counter variable by 1.
  • Thus, the length of the array will be stored in the counter variable as the variable will represent the number of elements in the list.

counter = 0 for item in list: counter+=1

print[counter]

Example:

inp_lst = [‘Python’,’Java’,’Kotlin’,’Machine Learning’,’Keras’] size = 0 print[“Length of the input string:”] for x in inp_lst: —-size+=1

—-print[size]

Output:

Length of the input string:
5

Find the length of a nested list in Python

Let us see how to find the length of a nested list. For this, we declared a list inside a list with the combination of a few other items. If we want the complete list length, then it considers the Nested list as one element. However, we can get the Nested list length using the index value. For example, the below code is finding the length of a nested list [20, 40, 50, 65, 22].

# Length of a String List

nestedList = [‘Krishna’, 20, ‘John’, [20, 40, 50, 65, 22], ‘Yung’, 11.98] print[“\n Original List = “, nestedList]

print[“Length of a Nested List = “, len[nestedList[3]]]

output:

Original List = [‘Krishna’, 20, ‘John’, [20, 40, 50, 65, 22], ‘Yung’, 11.98]
Length of a Nested List = 5

Find the length of a list of lists

# 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

Find the length of all items in 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

Find the length of string and dict  with len function in Python

In Python, we can also use the len function to get the length of a string. For example:
len[“Hello”] – This will return the value “Hello” has a length of five.

We can also use len to get length of dict.
len[dict] – It will return the number of items in dict.

len[{‘Name’:’Steve’, ‘Age’:30, ‘Designation’:’Programmer’}] – This will return 3.

Interview Questions of List length in Python 3

Here are some interviews questions on get length of list Python.

Q: What is “len function” time complexity?
Answer: len[] works in O[1] time as list is an object.

Q: How do I get the number of elements in a list?
Answer: Use python length method “len[]” to get the size of list. See below example of it.

# empty list items = [] items.append[“apple”] items.append[“orange”]

items.append[“banana”]

# Get and print number of elements in the list
print[len[items]]

Output: 3

Q: What is the best way to find the length of a list in Python 3?
Answer: The best way to find the length of List in python is to use Len[] function.

Q: How to get the Python length of the Array?
Answer: Python doesn’t have an array data type. Python is using a “List” data type instead of an Array. Both works the same but there are some differences.

Where Array is using in Java, C++ and other programming language and Lists are used in Python.

List being an integral part of Python day-day programming has to be learned by all the python users and having a knowledge of its utility and operations is essential and always a plus. So this article discusses one such utility of finding the no. of elements in a list.
 

Method 1: Naive Method

In this method, one just runs a loop and increases the counter till the last element of the list to know its count. This is the most basic strategy that can be possibly employed in the absence of other present techniques.
Code #1 : Demonstrating finding length of list using Naive Method

test_list = [ 1, 4, 5, 7, 8 ]

print ["The list is : " + str[test_list]]

print ["Length of list using naive method is : " + str[counter]]

Output : 

The list is : [1, 4, 5, 7, 8] Length of list using naive method is : 5

Method 2 : Using len[]



The len[] method offers the most used and easy way to find the length of any list. This is the most conventional technique adopted by all programmers today.

print["The length of list is: ", len[a]]

Output:  The length of list is: 4

print["The length of list is: ", n]

Output:  The length of list is: 3

Method 3 : Using length_hint[]

This technique is a lesser-known technique of finding list length. This particular method is defined in the operator class and it can also tell the no. of elements present in the list. 
Code #2 : Demonstrating finding length of list using len[] and length_hint[] 

from operator import length_hint

test_list = [ 1, 4, 5, 7, 8 ]

print ["The list is : " + str[test_list]]

list_len = len[test_list]

list_len_hint = length_hint[test_list]

print ["Length of list using len[] is : " + str[list_len]]

print ["Length of list using length_hint[] is : " + str[list_len_hint]]

Output : 

The list is : [1, 4, 5, 7, 8] Length of list using len[] is : 5 Length of list using length_hint[] is : 5

Performance Analysis – Naive vs len[] vs length_hint[]

When while choosing amongst alternatives it’s always necessary to have a valid reason why to choose one over another. This section does a time analysis of how much time it takes to execute all of them to offer a better choice to use.
Code #3: Performance Analysis 

from operator import length_hint

test_list = [ 1, 4, 5, 7, 8 ]

print ["The list is : " + str[test_list]]

start_time_naive = time.time[]

end_time_naive = str[time.time[] - start_time_naive]

start_time_len = time.time[]

list_len = len[test_list]

end_time_len = str[time.time[] - start_time_len]

start_time_hint = time.time[]

list_len_hint = length_hint[test_list]

end_time_hint = str[time.time[] - start_time_hint]

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 : 

The list is : [1, 4, 5, 7, 8] Time taken using naive method is : 2.6226043701171875e-06 Time taken using len[] is : 1.1920928955078125e-06 Time taken using length_hint[] is : 1.430511474609375e-06

Conclusion: 

In the below images, it can be clearly seen that time taken is naive >> length_hint[] > len[], but the time taken depends highly on the OS and several of its parameter. In two consecutive runs, you may get contrasting results , in fact sometimes naive takes  least time out of three.All the possible 6 permutations are possible.

 length_hint[] > naive > len[],

naive > len[]=length_hint[] 

naive > length_hint[] >len[] 

len > naive > length_hint[]  > naive


Article Tags :

Practice Tags :

Video liên quan

Chủ Đề