18th Sep 2023 10 minutes read Python Loops: A Comprehensive Guide for Beginners Luke Hande learn python python basics When writing your Python programs, you’ll have to implement for and while loops all the time. In this comprehensive guide for beginners, we’ll show you how to correctly loop in Python. Looping is a fundamental aspect of programming languages. It allows you to execute a piece of code repeatedly until some exit condition is met, at which point the program will move on to the next piece of code. In Python, there are two different types of loops: the for loop, and the while loop. Each loop has its own way of executing and exiting, and knowing when to use the correct loop is an important skill for beginner programmers. In this comprehensive guide, we’ll explain all you need to know about looping in Python. If you’re new to Python and are looking for some learning material to get you on your feet, check out the Python Basics track, which combines 3 courses aimed at beginners. Or consider the Learn Programming with Python track, which includes 5 courses full of interactive exercises designed to accelerate your learning. Python for Loops The Python for loop is used when you have a block of code you want to execute a fixed number of times. To execute a for loop, you need to start with an iterable, e.g. a list or an array. Then simply loop through the contents of the iterable. Let’s start by defining a list with some integers, which we can then loop through as follows: >>> data = [2, 5, 3, 7] >>> for element in data: ... print(element) ... print('finished') 2 5 3 7 finished In the first iteration of the for loop, the variable element gets assigned to the first value in the list; then it is printed to the console. This is repeated for every value in the list, at which point the loop finishes. Notice the print(element) code block is indented. Indentation tells the program what is inside the loop. Since the final line is not indented, it is outside the loop and only gets executed once when the loop is finished. To better understand the mechanics at work here, try indenting the print('finished') line so it’s inside the loop. Run the code again and see what happens. Finally, instead of using a simple print() statement, any other block of code or function can be executed inside the loop. for Loops with range() We mentioned previously that to execute a for loop, you need to start with an iterable. In the above example it was a list, but it can be many different data structures. You can even use some Python built-in functions. Let’s start by considering the range() function, which you’ll be using all the time for looping. It has three arguments: start, stop, and step. Only stop is required; the start and step arguments have default values of 0 and 1 respectively. Here’s how to execute a for loop using range(): >>> for index in range(1, 7, 2): ... print(index) 1 3 5 Here, we defined start = 1, stop = 7, and step = 2, which results in every second number between 1 and 7 being printed. Notice the loop finishes before the number 7, since the stop value isn’t included in the output of the range() function. In the next example, we’ll use the range() and len() built-in functions to execute a for loop, as shown below: >>> data = [2, 5, 3, 7] >>> for index in range(len(data)): ... print(data[index]) 2 5 3 7 The result of the loop is the same as the first example (without the print('finished') statement). Instead of iterating directly through the elements of the list, we iterate through indices generated from range(). The argument to range() is the length of the list – in this example, 4. We then use these indices to get the element of the list: data[index]. The above method is a little more convoluted than the first example, but the advantage is that you have access to both the index and the list element. To see this, a simple modification to the above example can also print the index: >>> data = [2, 5, 3, 7] >>> for index in range(len(data)): ... print(index, data[index]) 0 2 1 5 2 3 3 7 Since it’s common to need access to both the list index and element, there’s another handy built-in function to make this easier. We’ll explore this in the next section. for Loops with enumerate() The enumerate() built-in function can be used to get the same result as the previous example, but with less code. This makes it more efficient and readable, as shown below: >>> data = [2, 5, 3, 7] >>> for index, element in enumerate(data): ... print(index, element) 0 2 1 5 2 3 3 7 Remember, indexing in Python starts from 0. But in many cases, it’s more practical to print the first index as 1. This can be easily achieved by defining the start argument in the enumerate() function. Just do the following: >>> data = [2, 5, 3, 7] >>> for index, element in enumerate(data, start=1): ... print(index, element) 1 2 2 5 3 3 4 7 This function is super useful. We have some more details and examples of how it works in the article The enumerate() Function in Python. for Loops in reverse In some situations, you may want to loop through your iterable from back to front. There are a few ways to do this. If you have a list or array, you can use a fancy little slicing trick to reverse the iterable, then loop through it like normal: >>> data = [2, 5, 3, 7] >>> for element in data[::-1]: ... print(element) 7 3 5 2 Doing the list slicing like this is equivalent to defining the start, stop and step values, like we saw with the range() function. Having a step = -1 results in reversing the list. The same result can be achieved by taking advantage of another Python built-in, namely the reverse() function. Simply provide the list as the argument, and run the code block again to print the elements from back-to-front. The article How to Decrement a Python for Loop has more detailed examples of looping in reverse. Or, for some more examples of writing for loops with some different Python data structures, take a look at How to Write a For Loop in Python. Python while Loops The second type of loop in Python is the while loop, which allows you to iterate indefinitely. In contrast to for loops, while loops don’t require you to first define an iterator and then loop through it. The syntax of a while loop is as follows: >>> while True: ... print('Looping') If you run this code in your Python console, it will run indefinitely. You’ll need to manually kill the program, for example by hitting CTRL + C. In the above example, try changing the True to False. You’ll find the loop doesn’t run at all. In a real world case, if you provide an expression which evaluates to True (for example 2 < 3), the loop will run; if the expression becomes False (for example 3 < 3), the loop will stop. Now let’s see an example of function that actually ends: >>> number = 0 >>> while number < 3: ... print('Looping') ... number += 1 Looping Looping Looping Here, we had to first define number, then check if it’s less than 3. If so, we print something, then increase the number by one. The += operator is a convenient way to increment the value; in the above example it's equivalent to number = number + 1. As an exercise, take the previous example and modify it to print out the number as well, so you can see it increasing before the loop stops. By changing the condition, you can control how long the loop runs. There are some loop control statements which allow you to have fine-grained control over how your loops execute and when they exit. We’ll see some examples later, but before that we’ll look at nesting loops. Nested for and while Loops Until this point, we’ve only seen one level of looping. But loops can be nested to any depth. Take a look at the following example: >>> for i in range(3): >>> for j in range(3): ... print(i+j) 0 1 2 1 2 3 2 3 4 Here, we’re simply adding the indexes from the two iterables together. For this example, try modifying the print() statement to print out both indices and the result to show the whole mathematical expression (i.e. 0+0 = 0, 0+1 = 1, ... 2+2 = 4) to see exactly how it works. The different types of loops can be combined. We can re-create the output we got above by substituting the outer for loops with a while loop, as shown below: >>> i=0 >>> while i<3: ... for j in range(3): ... print(i+j) ... i+=1 0 1 2 1 2 3 2 3 4 If you have multiple Python lists, you can iterate over both of them with nested loops. But it’s also possible to loop over both lists in the same loop, as we show in How to Loop Over Multiple Lists in Python. Controlling for and while Loops in Python break The break statement is the first of three ways to get more fine-grained control over how your loops run. It is used with an if-elif-else statement to exit the loop early if a stated condition is met. Here’s an example of how it works: >>> for index in range(5): ... if index == 3: ... break ... else: ... print(index) 0 1 2 Normally, the loop should run longer, printing the numbers 0 – 4. The break statement stops the execution of the whole loop early if the condition defined in the if statement evaluates to True. Note: You can omit the else part and the loop will work exactly the same. continue The continue statement behaves a little differently. Instead of exiting early from the loop, it skips part of the loop and then continues until the loop naturally ends. Compare the following example to the previous: >>> for index in range(5): ... if index == 3: ... continue ... else: ... print(index) 0 1 2 4 When the loop reaches the continue statement, it skips the number 3. It then continues to print the final index and exit normally. Note: Here, you also can omit else – try it out! pass The pass statement is used as a placeholder in a block of code where nothing is supposed to happen. Say you want to implement a new function or loop, but want to come back later to fill in the logic. You can simply add a pass and the rest of the program will continue to run. An example is shown below: >>> for index in range(5): ... pass For some more examples of how to exit out of loops early, read the article How to End Loops in Python. Take Your Python Loops to the Next Level In this article, we looked at how to use Python loops to execute a piece of code repeatedly. Understanding how Python’s for and while loops work is fundamental to programming, since you’ll be using them all the time. But there are other methods, including list comprehension and lambda functions, that you can use to loop in Python. We show some examples in 7 Ways to Loop Through a List in Python. Or see the article Lists and List Comprehension in Python for some more in-depth reading. If you’re struggling to find good online content to learn Python, we’ve done the hard work for you. Check out Our 5 Favorite Free Python Online Courses for Beginners for some useful tips. Tags: learn python python basics