If you have used arrays in other programming languages, you can find something similar in the form of lists in Python. The only difference is that Python lists come with an additional benefit – dynamic size. Like arrays, you can use them to store more than one item.

Why Is Looping Required?

While working with lists, there will be times when you will need to perform the same operation against each entry in the list.

For example, you might want to take the mean of all entries in a list. On a similar note, what if you have stored blogs in a list and would like to fetch their headline?

All these scenarios have the same problem: they involve repetition. To address these concerns, you can simply use loops with lists in Python.

Let’s see how loops make it easy to perform operations against multiple items in a list with an example.

Understanding Loops with Lists Through an Example

Suppose you want to print a list of American Swimmers of the Year from 2016 to 2019 (no one was awarded in 2020 due to COVID-19). Without loops, you will have to retrieve each name one by one from the list. However, there are two major issues with this method:

  1. Printing each name is repetitive and time-consuming when you are working with a long list.
  2. Modifying the code for each instance requires considerable effort.

Related: How To Use a While Loop in Python

Fortunately, a for loop can address both these issues efficiently. Consider the following code:

        
swimmers = [<strong>'phelps'</strong>, <strong>'dressel'</strong>, <strong>'kalisz'</strong>, <strong>'dressel'</strong>]
<strong>for </strong>swimmer <strong>in </strong>swimmers:
print(swimmer)

Let’s dissect this code in three steps:

  1. You define a list swimmers and store the names of winners in it.
  2. You define a for loop, pull a name from the list swimmers one by one and assign it to the variable swimmer.
  3. You ask Python to print a name that is assigned to swimmer in that specific iteration.

Now, Python continues to reiterate the 2nd and 3rd steps to print all the swimmers in your list. For your convenience, you can read it like this: “For every swimmer in my list of swimmers, display the swimmer’s name.” Here’s the output:

swimmer-program-python-about-loops

A Brief Glance at Loops

The topic of looping is crucial because it is one of the core approaches for automating repetitive tasks. For instance, in our swimmers.py file, Python processes the loop’s first line:

        
<strong>for </strong>swimmer <strong>in </strong>swimmers:

Here, you tell Python to fetch the first value from your list, swimmers. Next, it assigns it to your defined variable swimmer. Since the first value is ‘phelps’, the following statement applies to it:

        
print (swimmer)

It is important to understand that Python is printing the most current value of swimmer at this stage, which happens to be ‘phelps’. As the list consists of multiple values, Python goes back to the first line of the loop:

        
<strong>for </strong>swimmer <strong>in </strong>swimmers:

This time, Python will fetch the next name from your list, ‘dressel’ and assign it to the variable swimmer. Again, Python will execute the following piece of code:

        
print (swimmer)

Now, Python prints the most current value of swimmer, which happens to be ‘dressel’. Similarly, Python will reiterate the loop and print ‘kalisz’ and ‘dressel’.

After printing the last value, Python goes to the first line of loop again, and since there is no further entry, it will move to the next line. In this program, there is nothing after the for loop, so it ends.

As you continue looping through lists, bear in mind that whatever the step you define in your code, it will be reiterated once for each list entry, regardless of the list’s length. That means that even if you add a billion entries to your list, Python will perform your defined action a billion times.

Another thing to note is that when you define your for loops, you can pick any name for the temporary variable assigned to each entry in the list. But, it’s recommended to pick a name that fits your context for better code readability.

For instance, here is an effective approach to loop through a list of products, birds, and actors:

        
for product in products:

for bird in birds:

for actor in actors:

Now that you have got a basic grasp of for loop, you manipulate each item of your list. Going back to the swimmer example, you can give compliments to each swimmer for their skills by writing the following code:

        
swimmers = ['phelps', 'dressel', 'kalisz', 'dressel']
for swimmer in swimmers:
print(f"{swimmer.title()}, your swimming skills are terrific!")

This code exactly works like the one before; the only difference is that you create a message for each swimmer by calling out their names. Like before, the loop runs again each swimmer and prints out a statement for each of them. As expected, the generated output is shown below:

Swimmer program loops with lists executing a print statement

You can also write multiple statements in the for loop. Keep in mind that the loop encompasses every indented line that comes after swimmer in swimmers, and Python executes each line once for every list value. Hence, there are endless possibilities for all the entries in the list.

For instance, you can write another print statement in the above example.

        
swimmers = ['phelps', 'dressel', 'kalisz', 'dressel']
for swimmer in swimmers:
print(f"{swimmer.title()}, your swimming skills are terrific!")
print(f"Looking forward to see your in the next competition, {swimmer.title()}.\n")

As you have used indentation for both statements, Python executes each of them for every entry in the list.

Python programs involving loops with lists executing multiple statements

After completing the loop, you can summarize your output and then move to other parts of your program. This post-loop part should not indented, so it is not repeated.

Now You Can Loop Through Lists Easily

In this article, you learned why loops are needed, how to use loops with lists, and how Python processes entries in a list when it is indented in a loop. You can now use lists and loops to write more complex code and create programs of higher quality.

To test your knowledge, here is a simple exercise: create a list of 10 numbers and print only numbers that are divisible by five.