Using Python Loop through list

In this short tutorial, we look at how to use Python to loop through a list. We break down the code so that you understand the concept thoroughly.

Table of Contents - Python loop through list

Python Loop Through List:

Quite often you might find yourself wanting to run through all the items in your list. This could be to either display the items or to perform a task on the items. An example of this would be to change the case of a list of strings or to perform arithmetic operations on a list of numbers.

In both cases, you are required to perform a single task over all the items in a list. Python provides a method to achieve this. Using a ‘for’ loop, we can make Python loop through the list and perform the task. This is the most efficient way to loop through a list with ease irrespective of whether the list contains 10 or 1000 items.

Code and Explanation:

Let's say we have a list containing the various colors of the rainbow.
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

Now let us assume we have to print each color in a different line. To achieve this manually, we would have to keep changing the index in our code for each color. However, by using the for loop we leave it to Python to loop through our list.

Let’s write the code to do that:
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

for color in colors:

This code iterates over the list and prints the colors in the list. Let’s take a closer look at what has happened here.
for color in colors:
This line tells Python to take the first value from the list colors and assign it with the variable color. And once that is done we move on to the next line.

Since ‘color’ now contains the first value which in our case is “red”, it gets printed. Python then looks to see if there are more elements in the list and since it does, it repeats the process again until it has done it for all the items.

To summarise what we have done here, we have assigned a list called colors and we create a for loop which tells Python that “for every color in the list of colors, print the color”.

Closing Thoughts:

As you may have noticed, we named our list “colors” (plural) and the variable in our for loop as “color” (Singular). This is a very good practice when it comes to naming as it would help make your code more readable.

However, this is only a best practice and any other variables would also work. Other tutorials may contain more concise but complex methods in Python to loop through a list, but I would recommend following this method as it is more readable. Once you have understood this feel free to try out more complex methods.

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

Copyright @2023 Flexiple Inc