While loop until the List is empty in Python

avatar

Borislav Hadzhiev

Last updated: Sep 20, 2022

banner

Photo from Unsplash

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
# ✅ while loop until the list is empty my_list = ['bobby', 'hadz', 'com'] while my_list: my_list.pop(0) print(my_list) # 👉️ [] # ------------------------------------------- # ✅ while loop until the list is empty with multiple conditions my_list = ['bobby', 'hadz', 'com'] count = 10 while my_list and count > 0: my_list.pop() count = count - 1 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
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.

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) # 👉️ []

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.

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.