Python is a very expressive language that provides different structures to easy developers work. The list is one of the most popular data structures provided by the python. In a regular workflow, we add and remove elements into and from the list. But in this floating situations, we need to get the length of the list. How can we get the length or size of the list? In this tutorial, we will look at different ways to get a list length.
Using Built-in len() Function
As we stated before
len is a builtin function provided python by default. We can use this function just providing the list as an argument like below. The syntax is very simple we will just provide the list, array, tuple or dictionary type variable into the
len() function as an array.
As we can the size of the list
pb is 3.
Get Multi Dimension List Length
In previous we have looked at the length of a single dimension list. But in real-world situations, there will be multi-dimension lists. We can also get the length of this list single dimension length just providing the index of the related sub-list like below. In this example, we want to get the length of the first sub-array.
We provide the sublist element index as
0 which is
['ismail','elif'] and get the length of this sub-list as
Count Length with For Loop By Iterating Each Element
len() function provides a very convenient, easy and efficient way to get the length or size of an array. But in some cases, we may want to calculate a list length or size by counting it one by one. Even we want to eliminate some elements in a list and do not count them. In this example, we can achieve this by using
for loop with a list.
pb=['ismail','ahmet','ali'] count=0 for element in pb: count=count+1 print(count) #3
len() function is very useful where it can be used to get the length or size of different array types like the dictionary. We can use the same syntax to count dictionary key, value type elements. This will count 1 a single key and value pair.