Lecture
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.
Lessons in this chapter · While Loops and List Comprehensions
- 1. How to Execute a Loop While a Given Condition is True
- 2. Controlling Logic Flow Inside Loops
- 3. Using While Loops with Lists
- 4. Multiple-choice quiz
- 5. Calculating Minimum, Maximum, and Sum
- 6. How to Reverse the Order of Objects
- 7. Iterating Over Elements of an Iterable
- 8. Iterating Over Key-Value Pairs with the items() Function
- 9. Simplifying Lists with List Comprehensions
- 10. Using the join() Function to Concatenate Strings
- 11. Differences Between Iterables and Iterators
- 12. Coding Quiz - Determine Odd/Even
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
Quiz
0 / 1
A while loop can iterate through each element of a list and process them based on a specific condition.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help