Python while list is not empty | Example code

You can give a condition expression in while to test list is empty or not or you can use if statement for it.

Python while list is not empty Examples

Simple example code. While loop iterate list until a list length is 0.

list1 = [1, 2, 34, 44]

l = len(list1)
while l >= 0:
    print("Not empty", l)
    l = l - 1

Output:

Python while list is not empty

Python While Loop until the list is empty example

While Loop run until the list is empty. Using a pop method to remove every time element in the loop.

list1 = [1, 2, 34, 44]

while len(list1) > 0:
    print(list1)
    list1.pop()

print(list1)

Output:

[1, 2, 34, 44]
[1, 2, 34]
[1, 2]
[1]
[]

Check if the list is an empty python

list1 = []

if len(list1) == 0:
    print('the list is empty')

Output: the list is empty

Do comment if you have any doubts and suggestions on this Python list while the topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.