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 of 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.
name_list=['ismail','ahmet','ali']
len(name_list)
fruit_list = ['apple', 'banana', 'carrot' , 'melon' , 'tomato']
len(fruit_list)
number_list = [1,2,3,4,5,6,7,8,9,10,12,13,14,15]
len(number_list)

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.
name_list=[['ismail','elif'],'ahmet','ali',[7,8,9,10],1,2,3,['apple', 'banana', 'carrot' , 'melon' , 'tomato']]
len(name_list)
len(name_list[0])
len(name_list[7])

We provide the sublist element index as 0
which is ['ismail','elif']
and get the length of this sub-list as 2
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.
name_list=['ismail','ahmet','ali']
count=0
for element in name_list:
count=count+1
print(count)
name_list=[['ismail','elif'],'ahmet','ali',[7,8,9,10],1,2,3,['apple', 'banana', 'carrot' , 'melon' , 'tomato']]
count=0
for element in name_list:
count=count+1
print(count)

Dictionary Length
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.
name_surname={'ismail':'baydan','ahmet':'baydan','ali':'baydan'}
len(name_surname)

hiya
hiya
heading “Dictionary Lenght”
should be “Dictionary Length”
Hi,
Thanks for the help.