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

Last updated: Apr 13, 2024
6 min

## #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
```Copied!```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)
``````

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
```Copied!```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
```Copied!```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)
``````

## #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
```Copied!```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
```Copied!```1
3
5
``````

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
```Copied!```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, 1, 2, 1, 1, 2, 3, 4]
print(a_list)

# ๐๏ธ 5
print(num)
``````

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

## #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
```Copied!```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
```Copied!```1
2
3
``````

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
```Copied!```my_list = ['bobby', 'hadz', 'com']

while my_list:
my_list.pop(0)

print(my_list)  # ๐๏ธ []
``````

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
```Copied!```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
```Copied!```my_list = ['bobby', 'hadz', 'com']

my_list.pop()

``````
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
```Copied!```my_list = ['bobby', 'hadz', 'com']

count = 10

while my_list and count > 0:
my_list.pop()

count = count - 1

print(my_list)  # ๐๏ธ []
``````

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
```Copied!```my_list = None

for item in my_list or []:
print(item)
``````

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
```Copied!```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
```Copied!```my_list = ['bobby', 'hadz', 'com']

for item in my_list or []:
# bobby
# 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
```Copied!```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.