Skip to main content
Practice

Using While Loops with Lists

Using a while loop with a list allows you to iterate over its elements and process them based on specific conditions.

The code below iterates over the elements of the numbers list. It prints "Found it" if an element is 3, "Even" for even numbers, and "Odd" for odd numbers.

Conditional Element Processing
numbers = [1, 2, 3, 4, 5]

while numbers:
# Store the last element of the list in the num variable
num = numbers.pop()
if num == 3:
print(f"Found it: {num}")
elif num % 2 == 0:
print(f"Even: {num}")
else:
print(f"Odd: {num}")

The while loop is suitable for cases where the size of the list changes during code execution.

In the example above, since the pop() method retrieves elements from the numbers list, reducing its size, the while loop continues until all elements are processed.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.