Length Of A List Python
Now, we are going to learn about how we can find the length of the list. First of all, Let’s try to define what is length, in the case of a list. Basically, the length of a list is the number of elements/items in the list. To get the length of the list, we just have to make use of the len function, which simply tells us the length of the list. The len function takes an argument, where we can simply pass the list, and then it returns the length of the list.
Now, Let’s have a look at a simple program, which demonstrates getting the length of the list, using the len function.
Length Of A List Python
As you can see, we have a list, with some different elements. We can simply tell just by looking at the list, that there are 6 elements in the list. Also notice that the list here contains the data of multiple datatypes. After that, we have called the len function, to which, we are passing the list as an argument. The len function returns the length of the list, which is being assigned to the variable list_length(you can directly print the return value from the len function, but just to demonstrate that it returns something, we have assigned the length value to some variable).
After that, we are simply printing the value from the list_length variable, which has the length of the list. If we try to run the above program, the output simply comes out to be 6, since the list has 6 elements here.
So, using the len function, we can simply find the length of the list. Note that the length of list means the number of elements in the list. At times, we might require getting the length of the list, and in such situations, we would make use of the len function.
Alternatively, we can also get the length of the list, without using the len function. But here, we need to iterate through the list, using the for loop, and increment the count accordingly. Have a look at the below program, which tries to demonstrate the same thing.
As you can see in the above program, we have the same list, and then we also have a variable, which would hold the length of the list. Then, we are iterating through the list, and for every element, we are incrementing the value in the list_length variable, and after we are out of the loop, we are printing the length of the list.
So, this was about getting the length of the list, which is nothing but the number of elements in the list. We saw two ways to get the length of the list. You would see that much often, when we need to get the length of the list, we would simply make use of the len function. So, you can also try for some different lists, in your programs, and try the len function, while we move forward exploring more about list.