The len() method for getting the length of a list

The Python has a built-in method len() for getting the total number of items in a list, tuple, arrays, dict etc. The len() method takes an argument where you may provide a list and it returns the length of given list.

A list length example  length of Array example

Syntax for using the Python len() method

This is how you may use the len() method of Python:

len(s)

For example, we have a list:

A_list = [5, 10, 15, 20, ‘a’, ‘b’, ‘c’]

This is how you may use the len() method for getting the length of that list:

List_length = len(A_list)

See the following examples of using this len() method for getting the length of lists, array, dictionary, and tuple.

An example of getting list length

In this example, a list is created with a few items. The items are the combination of numbers and string characters. This is followed by using the len() method. The returned value is assigned to a variable and its value is displayed by using the print function. See the code and output of this example:

See online demo and code

 

Python list length

You can see, the length of the list is returned as 8.

An example of using len method in for loop

In this example, a list of strings is created. After that, a for loop is used to get the length of each string item in the list. Basically, it will not only return the total length of the list but the length of each string item in the list by using the len() method. Have a look:

See online demo and code

 

len

Is len() method specific to the list?

No, by definition, the argument of the len() method may be a sequence e.g. a string, list, byte, tuple, range etc). You may even provide a collection as a parameter.

So, by using the len() method you may also get the length or total number of items in a set, dictionary or frozen set etc.)

The following section shows examples of using len() method in different sequences and collections.

Getting the length of an array example

The following example shows how to get the length of an array. First, an array is created after importing the array module. After that, the len() method is used to get the array length which is displayed by using the print function:

See online demo and code

 

array length

You can see, the array which type is integer contains five elements.

A len method example with a tuple

See this example where a tuple is created with string elements. The len() method is used to get the number of items in the tuple:

See online demo and code

 

tuple length

Using len() method with a dictionary

Similarly, you may use the len() method with dictionary collection for getting the total number of items in the dictionary. See the demonstration below:

See online demo and code

 

dictionary length