Python len list

In Python the len method on the list allows us to get the number of elements in a list, ultimately it indicates the length of a list in Python.

The syntax of the method is very simple:

len(list)

The function takes only one parameter, the list to calculate the length of. This parameter is mandatory.

Python len list – first example

Let’s create a practical example of using the function for calculating the length of a list in Python.

Let’s first create a list that contains the seasons:

seasons = [‘Spring’, ‘Summer’, ‘Autumn’, ‘Winter’]

Then we apply the len function on the Python list element:

len(seasons)

We can also print the value using print:

print(len(seasons))

The result will be 4.

We can also use a variable to store the result:

len_stagioni = len(seasons)

Then, later on, we will use the variable_season within our program, such as for example.

print(len(seasons))

Python len list – second example

Calculating the length of a list is very useful when we need to iterate.

For example, suppose you want to print all the elements of a list. In our case of seasons.

At first I present an incorrect approach to the problem, explaining the reasons.


seasons = ['Spring', 'Summer', 'Autumn', 'Winter']
for i in range(4):
   print(seasons[i])

In this case, the code could also be fine, because I will never add another season to the list. But think of lists that can be easily expanded by adding more elements.

To make everything work, I will have to change the parameter within the range every time! But does it seem correct to you? I would say no!

So how do I solve the algorithm? Using the len function on the list, like so:


seasons = ['Spring', 'Summer', 'Autumn', 'Winter']
for i in range(len(seasons)):
   print(seasons[i])

We can also use the variable to store the length of the list.


seasons = ['Spring', 'Summer', 'Autumn', 'Winter']
len_seasons = len(seasons )

for i in range(len_seasons):
   print(seasons[i])

The len function, for calculating the length of a list in Python, as we will see later, will be very useful when we want to populate the elements of the list without producing duplicates. Follow me in the next tutorials to find out how!

Conclusion

In developing the exercises we will develop many exercises using the len function on the Python list element.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *