How to restart a Loop in Python [3 Simple Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 13, 2024
6 min

banner

# Table of Contents

  1. How to restart a Loop in Python
  2. If you need to skip an iteration of a loop, use a continue statement
  3. If you want to exit a loop prematurely, use the break statement
  4. While loop until the List is empty in Python

# How to restart a Loop in Python

To restart a loop in Python:

  1. Use a while loop to iterate for as long as a condition is met.
  2. In the while loop check if another condition is met.
  3. If the condition isn't met, restart the while loop by resetting the variable to its initial value.
main.py
import random num = 1 a_list = [] while num < 5: if random.uniform(0, 1) > 0.5: num += 1 a_list.append(num) else: a_list.append(num) num = 1 # ๐Ÿ‘‡๏ธ [1, 1, 2, 2, 1, 1, 1, 1, 2, 3, 3, 1, 2, 3, 4, 5] print(a_list) # ๐Ÿ‘‡๏ธ 5 print(num)

restart loop in python

The code for this article is available on GitHub

The while loop iterates for as long as the num variable is less than 5.

In the if statement, we used the random.uniform() method to generate a random number from 0 to 1.
main.py
while num < 5: if random.uniform(0, 1) > 0.5: num += 1 a_list.append(num) else: a_list.append(num) num = 1

A random number is used to simulate a condition. This could be any other condition that suits your use case.

If the generated number is greater than 0.5, we increment the num variable and append it to the list.

If the condition isn't met, the else block runs where we append the number to the list and reset the while loop by setting num to 1.

The while loop will only finish running when the num variable is set to 5 or a number greater than 5.

You don't necessarily have to increment the num variable in the if block.

You could increment it after the if and else blocks.

main.py
import random num = 1 a_list = [] while num < 5: if random.uniform(0, 1) > 0.5: a_list.append(num) else: a_list.append(num) num = 1 num += 1 # ๐Ÿ‘‡๏ธ [1, 2, 2, 2, 2, 2, 3, 4] print(a_list) # ๐Ÿ‘‡๏ธ 5 print(num)

incrementing n after the if else blocks

The code for this article is available on GitHub

# Table of Contents

  1. If you need to skip an iteration of a loop, use a continue statement
  2. If you want to exit a loop prematurely, use the break statement
  3. While loop until the List is empty in Python

# If you need to skip an iteration of a loop, use a continue statement

If you need to skip an iteration of a loop, use the continue statement.

main.py
a_list = [1, 2, 3, 4, 5] for num in a_list: if num % 2 == 0: continue else: print(num)

Running the code sample produces the following output.

shell
1 3 5

use continue statement to skip loop iteration

The code for this article is available on GitHub

The continue statement continues to the next iteration of the loop.

In other words, it basically skips the iteration.

In the example, we check if each number is divisible by 2 and if the condition is met, we skip the iteration.

The continue statement can be used in for and while loops.

You can also use the continue statement when restarting a loop.

main.py
import random num = 1 a_list = [] while num < 5: if random.uniform(0, 1) > 0.5: a_list.append(num) else: a_list.append(num) num = 1 continue # ๐Ÿ‘‰๏ธ skip to next iteration num += 1 # ๐Ÿ‘‡๏ธ [1, 1, 2, 1, 1, 2, 3, 4] print(a_list) # ๐Ÿ‘‡๏ธ 5 print(num)

using continue when restarting loop

The code for this article is available on GitHub

We used the continue statement in the else block to skip to the next iteration and not run the num += 1 line.

# Table of Contents

  1. If you want to exit a loop prematurely, use the break statement
  2. While loop until the List is empty in Python

# If you want to exit a loop prematurely, use the break statement

If you need to exit a loop before it has finished running, use the break statement.

main.py
a_list = [1, 2, 3, 4, 5] for num in a_list: if num > 3: break else: print(num)

Running the code sample produces the following output.

shell
1 2 3

exit loop before finished running with break

The break statement breaks out of the innermost enclosing for or while loop.

I've also written an article on how to use a For or While loop to take user input in Python.

# While loop until the List is empty in Python

To use a while loop until the list is empty:

  1. Use a while loop to iterate as long as the list contains items.
  2. Use the list.pop() method to remove items from the list.
  3. The while loop will iterate for as long as the list is not empty.
main.py
my_list = ['bobby', 'hadz', 'com'] while my_list: my_list.pop(0) print(my_list) # ๐Ÿ‘‰๏ธ []

while loop until list is empty

The code for this article is available on GitHub

The first example uses a while loop to iterate over a list and empties the list.

The while loop iterates as long as the list is not empty.

We could have also explicitly checked for the list's length.

main.py
my_list = ['bobby', 'hadz', 'com'] while len(my_list) > 0: my_list.pop(0) print(my_list) # ๐Ÿ‘‰๏ธ []

On each iteration, we use the list.pop() method to remove an item from the list.

The list.pop() method removes the item at the given position in the list and returns it.

main.py
my_list = ['bobby', 'hadz', 'com'] my_list.pop() print(my_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz']
If no index is specified, the pop() method removes and returns the last item in the list.

If you call the list.pop() method with an index of 0, items from the start of the list get removed.

If you call the list.pop() method without any arguments, items from the end of the list get removed.

# While loop until the list is empty based on multiple conditions

If you need to specify multiple conditions in the while loop, use the and boolean operator.

main.py
my_list = ['bobby', 'hadz', 'com'] count = 10 while my_list and count > 0: my_list.pop() count = count - 1 print(my_list) # ๐Ÿ‘‰๏ธ []

while loop until list is empty based on multiple conditions

The first condition in the while loop checks if the list is not empty and the second checks if the count variable stores a value greater than 0.

We used the boolean AND operator, so for the code in the while block to run, both conditions have to be met.

You can use this approach to specify as many conditions as necessary in a while loop.

If you need to check if a list variable is declared or if a list is empty before iterating over it, use the boolean OR operator to provide a fallback.

# Use a for loop if the list isn't empty in Python

If you need to use a for loop if a list isn't empty, use the or operator.

main.py
my_list = None for item in my_list or []: print(item)
The code for this article is available on GitHub

We used the boolean OR operator to provide a fallback value in case the variable stores a falsy value.

The expression x or y returns the value to the left if it's truthy, otherwise, the value to the right is returned.
main.py
print(['a', 'b'] or []) # ๐Ÿ‘‰๏ธ ['a', 'b'] print(None or []) # ๐Ÿ‘‰๏ธ [] print(False or []) # ๐Ÿ‘‰๏ธ []

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

So if the value to the left is any of the aforementioned falsy values, the value to the right is returned.

Lists that contain values are truthy, so the for loop would iterate over the list if it contains at least one element.

main.py
my_list = ['bobby', 'hadz', 'com'] for item in my_list or []: # bobby # hadz # com print(item)

If you need to perform an action for every item in a list if it's not empty, you can also use a list comprehension.

main.py
my_list = [2, 4, 6, 8] new_list = [number * 2 for number in my_list or []] print(new_list) # ๐Ÿ‘‰๏ธ [4, 8, 12, 16]

We used the or operator to provide an empty list as a fallback in case the value stored in the variable is falsy.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we multiply the current number by 2 and return the result.

I've also written an article on how to remove elements from a list while iterating.

Want to learn more about working with loops in Python? Check out these resources: How to Add elements to a List in a Loop in Python,Adding items to a Dictionary in a Loop in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev