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:
## For Loop example #1 print('Repeat after me:') for encouragement in range(3): print('We will get better at coding (' + str(encouragement) + ')')
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.
Repeat after me: We will get better at coding (0) We will get better at coding (1) We will get better at coding (2)
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:
# List example #1 food = ['burger', 'pizza', 'pasta', 'bacon omelette']
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.
Here’s how we access each index number.
## List example #1 ['burger', 'pizza', 'pasta', 'bacon omelette'] food = ['burger', 'pizza', 'pasta', 'bacon omelette'] print(food[0]) #Return value burger
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.
coders = ['Zack', 'Jesus', 'Dan', 'You'] for i in range(len(coders)): print('Index ' + str(i) + ' in the coder list is: ' + coders[i]) print(coders[i] + ' ' + 'will get better at coding!')
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:
Index 0 in the coder list is: Zack Zack will get better at coding! Index 1 in the coder list is: Jesus Jesus will get better at coding! Index 2 in the coder list is: Dan Dan will get better at coding! Index 3 in the coder list is: You You will get better at coding!
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
.
food = ['burger', 'pizza', 'pasta', 'bacon omelette'] for dish in food: print(dish) if dish == 'pasta': break burger pizza 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:
while True: print("Please enter your login ID") login_id = input() if login_id != "Dan": continue print("Welcome back, Dan. Please enter your password") password = input() if password == "psw123": break print("Thank you. Access Granted.")
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.
newfood3 = ['sushi', 'kebab', 'capacollo', 'lasagna', 'grilled cheese', 'jelly', 'popcorn', 'ham'] try: newfood3.remove('lasagna') except ValueError: pass print(newfood3) ['sushi', 'kebab', 'capacollo', 'grilled cheese', 'jelly', 'popcorn', 'ham']
You can also use a List Comprehension that removes all the elements that match a specific condition.
newfood = ['burger', 'bacon omellete', 'tacos', 'salad', 'lasagna', 'lasagna', 'lasagna', 'lasagna'] newfood = [x for x in newfood if x != 'lasagna'] print(newfood) ['burger', 'bacon omellete', 'tacos', 'salad']
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:
desserts = ['chocolate cake', 'vanilla cake', 'ice cream'] desserts.append('apple pie') print(desserts) ['chocolate cake', 'vanilla cake', 'ice cream', 'apple pie']
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:
list1 = ['lasagna','manicotti','cannolis'] list2 = ['riccota pie','escarole'] for item in list2: list1.append(item) print (list1) ['lasagna', 'manicotti', 'cannolis', 'riccota pie', 'escarole']
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:
list1 = ['lasagna','manicotti','cannolis'] list2 = ['riccota pie','escarole'] list3 = [] for item in list1: list3.append(item) for item in list2: list3.append(item) print (list3) ['lasagna', 'manicotti', 'cannolis', 'riccota pie', 'escarole']
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:
calculuslist1 = [3,6,9,12,15] calculuslist2 = [] for number in calculuslist1: calc = number * 10 calculuslist2.append(calc) print(calculuslist2) [30, 60, 90, 120, 150]
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.
for i, val in enumerate(coders): print (i, ":",val) 0 : Zack 1 : Jesus 2 : Dan 3 : You
Here’s the output for our original loop:
Index 0 in the coder list is: Zack Zack will get better at coding! Index 1 in the coder list is: Jesus Jesus will get better at coding! Index 2 in the coder list is: Dan Dan will get better at coding! Index 3 in the coder list is: You You will get better at coding!
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:
listComp = [22, 44, 66, 88, 110] print([item * 2.0 for item in listComp]) [44.0, 88.0, 132.0, 176.0, 220.0]
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 while
loop 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
orFalse
- A clause
Here’s what a while
loop looks like:
greetings = 0 while greetings < 5: print('Hello there!') greetings = greetings + 1 Hello there! Hello there! Hello there! Hello there! Hello there!
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!
lunch_order = [] while True: print('Enter dish #' + str(len(lunchOrder) + 1) + ' (Or enter nothing to stop.):') dishes = input() if dishes == ' ': break lunchOrder = lunchOrder + [dishes] print('Here is your order:') for dishes in lunchOrder: print(' ' + dishes)
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:
Enter dish #1 (Or enter nothing to stop.): manicotti Enter dish #2 (Or enter nothing to stop.): cannolis Enter dish #3 (Or enter nothing to stop.): apple pie Enter dish #4 (Or enter nothing to stop.): chocolate cake Enter dish #5 (Or enter nothing to stop.): Here is your order: manicotti cannolis apple pie chocolate cake
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.