3.6. Using a while Loop with Lists and Dictionaries
A for loop is effective for looping through a list, but you shouldn't modify a list inside a for loop because Python will have trouble keeping track of the items in the list. To modify a list as you work through it, use a while loop. We'll look at some examples.
Moving Items from One List to Another
Consider a list of newly registered but unverified users of a website. One way to move them to a separate list is using while loop. We begin with a list of unconfirmed users and an empty list. Here's what that code might look like:
Removing All Instances of Specific Values from a List
We learned that remove() can be used to remove a specific value from a list. That command worked because the value we want to remove only appear once. If the value appear more than once, we can put remove() inside a while loop as follows:
Exercise 3.6
Deli
- Make a list called sandwich_orders and fill it with at least five names of various sandwiches. You can choose from this list:
cheese sandwich, club sandwich, Dagwood, French dip, hamburger, Monte Cristo, muffuletta, pastrami, submarine.
- Then, make an empty list called finished_sandwiches.
- Loop through the list of sandwich orders and print a message for each order:
I made your {sandwich name}.
- After all the sandwiches have been made, print a message listing each sandwich that was made:
The sandwiches in your order are:
- cheese sandwich
- club sandwich
and so on.No Pastrami
- Using the list from no.1, make sure the sandwich 'pastrami' appears in the list at least three times.
- Print a message saying
The deli has run out of pastrami.
Then, use a while loop to remove all occurrences of 'pastrami' from sandwich_orders.
- Make sure no pastrami sandwiches end up in finished_sandwiches. Then print the remaining sandwiches like this:
The remaining sandwiches in your order are:
- cheese sandwich
- club sandwich
and so on.