Last updated: Apr 13, 2024
Reading timeยท6 min
To restart a loop in Python:
while
loop to iterate for as long as a condition is met.while
loop check if another condition is met.while
loop by resetting the
variable to its initial value.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
.
if
statement, we used the random.uniform()
method to generate a random number from 0 to 1.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.
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.
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)
continue
statementIf you need to skip an iteration of a loop, use the continue statement.
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.
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.
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)
We used the continue
statement in the else
block to skip to the next
iteration and not run the num += 1
line.
break
statementIf you need to exit a loop before it has finished running, use the break statement.
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.
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.
To use a while
loop until the list is empty:
while
loop to iterate as long as the list contains items.list.pop()
method to remove items from the list.while
loop will iterate for as long as the list is not empty.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.
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.
my_list = ['bobby', 'hadz', 'com'] my_list.pop() print(my_list) # ๐๏ธ ['bobby', 'hadz']
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.
If you need to specify multiple conditions in the while
loop, use the and
boolean operator.
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.
If you need to use a for loop if a list isn't
empty, use the or
operator.
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.
x or y
returns the value to the left if it's truthy, otherwise, the value to the right is returned.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:
None
and False
.0
(zero) of any numeric type""
(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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: