13 Ways to Loop Through a List in Python

Loops are the backbone of many computer programs and provide developers with a robust and concise syntax to manage complex flow control. Python affords several tools by which different loops structures can be used, exited, and controlled for maximum efficiency.

Dan Aveledo
alpharithms
9 min readSep 28, 2022

--

Loop Through a List in Python
Image: Alpharithms

Learn how to loop through a list in Python in record time with our short, step-by-step guide! Learning how to loop through a list in Python is a basic yet incredibly powerful building block that you’ll use throughout your career as a programmer.

It’s an excellent starting point for coders who wish to understand how loops and mutable data structures work and, more importantly, how to use them to automate a wide variety of tasks.

Loop Through a List in Python

Loops in Python cut down on redundant codes and repetitive commands, allowing you to perform a staggering number of tasks with just a few lines of code. On the other hand, Lists are ordered data structures that you can modify on the fly and can contain a tremendous number of values.

When you combine a list with a loop, you can perform operations on every single entry on your list, even if your list has thousands or even millions of items. This is why a loop through a list in Python becomes an outstanding automation tool that every successful programmer must master.

  • The for keyword
  • A variable
  • The in keyword
  • A call to the range function
  • A clause

Here’s what a for loop looks like:

Our example for loop sets the variable encouragement to 0. Then, the clause prints, We will get better at coding (0). It then returns to the beginning of our for loop, where the for statement increments encouragement by one.

The code goes through three iterations, where encouragement is set to 0, then 1, and 2. Notice that the variable encouragement will go up but won’t include the integer passed to the range() function. Now let’s look at lists to see how they can work with a for loop!

Looping List in Python

A list is a value that contains multiple items in an ordered sequence. We’ve discussed this essential data type in a previous piece, which I highly encourage you to check out!
A list value (the list itself, which includes all its individual items) looks something like this:

Now, I’ll assign this list to a variable called food. Notice that a comma separates each item in our list food. This is important because once we store in a variable, each comma-delimited item will have a corresponding index number.

Image: Alpharithms

Here’s how we access each index number.

The integer contained in the square brackets is the index. Accessing food[0] will return the first item in the food list, which is burger. Now that we’ve covered the fundamentals behind loops and lists let’s see how we can make them work together in a Python for loop!

For Loop in Python with List

Using a for loop in combination with the range() function is the most common (and easiest) way to loop through a list in Python. I’ve gone ahead and added all of us to a new list called coders. I’ll modify the original for loop that I showed you earlier so that it interacts with this new list.

For this next example, I’ll use range(len(coders)), since my variable i (short for item) will access the index and the item at that index as coders[i]. I’ve also asked our program to give us some much-needed encouragement throughout our journey! This is what our terminal shows:

This line of code will also iterate through all the indexes of the list coders. By default, the range function starts at 0 and then increments its value by 1 until the number that we’ve specified in our clause is reached. Note: The final value is not included in the output. This is referred to as an “exclusive” bound in that the upper bound is excluded.

‘Break’ in Python Loop

An infinite loop that never exits is a fairly common programming bug. Thankfully, there’s a shortcut that gets the program to break out of a loop. What’s best is that break keyword in Python loop works in for loops and while loops.

For our exiting for loop in Python example, we’ll modify our initial for loop demonstration, where we asked Python to print all the items in the food list. Now, we will ask our program to break out of the loop once it finds and prints pasta.

Notice how bacon omelette is no longer printed on our terminal window. This means we’ve successfully broken out of a loop that would’ve otherwise printed every item on our list!

The Continue Statement

The continue statement, just like the break statement, can only be used inside loops. Contrary to break, the continue statement forces the program to immediately jump back to the start of the loop and re-evaluate the loop’s condition.

In for loops, you can use the continue keyword to force the program to proceed to the next value in the counter — effectively skipping values at your convenience. An equally common and basic use of the continue statement is for creating a login and password that grants users access to your program’s functions. Here’s an example:

Python Remove Item From List in For Loop

Generally speaking, you do not want to remove items from a list while iterating over it. An alternative approach is realized by building a new list that filters undesired items. However, as shown below, you can attempt to remove the undesired elements coupled with a ValueError exception.

You can also use a List Comprehension that removes all the elements that match a specific condition.

Python Create Lists in For Loop

Python allows you to append items from one list to another or create entirely new lists with a for loop. We’ll go over a couple of ways to do this using the append() method.
You can use the append() method to add arguments to the end of the list as follows:

If you’d like your for loop to merge two lists, we can ask Python to append all the items in list 1 to list 2 with a for loop. Here’s an example:

If we want to Python create lists in for loop, we can also define an entirely new list and append all previous items to it. Here’s how I did it:

You can also modify this code to make all sorts of calculations and append all the results to a new list. Here’s another way for Python to create lists in for loop:

With these Python create lists for loop techniques, you can create entirely new lists and append items or results to them.

Loop in Python List with Enumerate

We used the range function for our first for loop example and added a string to our code that identified each item with its corresponding index. As it turns out, there’s a loop in Python list that can automatically do this for us.

When we combine the enumerate() method with a for loop, we can iterate each item in our list by index. This is particularly useful when we need to track both the index and value of each element. Let’s use our original coders list and compare their outputs.

Loop With List Python

Another popular loop with list Python comes via list comprehension. We briefly used this handy resource earlier to filter out items in a list with a loop.

A list comprehension can iterate through lists to access (or outright change) items and list values. This saves you the trouble of using the append method to new lists, saving you considerable time. Let’s take a closer look at how this loop with list Python works:

When used correctly, list comprehensions can make your code leaner and easier to understand.

Looping Through a List in Python With While Loops

You can also loop through your lists with a traditional while loop. A whileloop will execute a block of code over and over as long as the while statement condition is True. A while loop has:

  • The while keyword
  • A condition that evaluates to True or False
  • A clause

Here’s what a while loop looks like:

This while loop stops after five prints because the integer in greetings is incremented by one at the end of each loop iteration. Once the next iteration begins, the condition is checked, and if it evaluates to True, then the clause is executed once more. The cycle continues until the condition is found to be False.

We can use a while loop to create lists that work with our user’s input. Since most of our lists have featured popular foods and dishes, let’s create an automated service that takes your lunch order!

This while loop will take your customer’s order – one dish at a time – and concatenate the dishes into a lunch_order list. Customers can input an empty space to break the loop. Here’s what it would look like:

Note: Using a while True loop (a.k.a. infinite loop) is considered a code smell and bad practice by many. Unless one has a specific reason for which a loop should use the while True condition it is recommended to always have an explicitly-stated condition that could conceivably evaluate False.

Final Words

Lists are, by far, one of the most powerful data structures in Python. Combined with loops, they can automate a tremendous amount of work in just a few lines of code. A well-coded loop through a list in Python will allow you to create complex calculators and input-dependent programs that save you time and effort while dramatically improving its users’ experience.

The article 13 Ways to Loop Through a List in Python first appeared on the alpharithms website and has been republished here with permission.

--

--