← Python lessons

Python while Loop Over a List: pop() Until Empty

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A work list is a list of jobs still to do. A while loop takes jobs off it until it is empty, and may add new jobs as it goes.

Read While Loops and Lists first. The last example also uses in from Membership Testing and continue from break and continue. Every block below runs on its own with fixed data, and its output is described under it.

Loop until a list is empty

An empty list counts as false, so while tasks: keeps going while jobs remain. pop(0) removes and returns the first item.

tasks = ["wash", "dry", "fold"]
while tasks:
    task = tasks.pop(0)
    print("Doing", task)
print("All done")

Each pass removes one job, so the list shrinks to [] and the loop stops.

Choose pop(0) or pop()

pop(0) takes the oldest job first, like a queue. pop() takes the newest job first, like a stack of plates.

tasks = ["wash", "dry", "fold"]
while tasks:
    print(tasks.pop())

This prints fold, dry, then wash. Pick the order your problem needs.

Add jobs while looping

Opening one box can reveal more boxes. Each new box goes on the end of the list.

inside = {
    "crate": ["bag", "tin"],
    "bag": ["purse"],
    "tin": [],
    "purse": [],
}
to_open = ["crate"]
while to_open:
    box = to_open.pop(0)
    print("Opening", box)
    for item in inside[box]:
        to_open.append(item)

This opens crate, bag, tin, then purse. A for loop over to_open would be the wrong tool: changing a list while a for loop walks it skips or repeats items. The while loop checks the list fresh each time.

Avoid looping forever

If jobs can point back to earlier jobs, the list never empties. Keep a seen list and skip anything already done. continue jumps straight back to the while check.

links = {
    "home": ["about", "shop"],
    "about": ["home"],
    "shop": ["home", "about"],
}
to_visit = ["home"]
seen = []
while to_visit:
    page = to_visit.pop(0)
    if page in seen:
        continue
    seen.append(page)
    print("Visiting", page)
    for link in links[page]:
        to_visit.append(link)

Without the seen check, home and about would be added again and again. Each page is visited once.

Note: pop(0) on a long list is slow, because every other item shifts down. Real programs use collections.deque and its popleft() for large queues. These examples use small fixed dictionaries; real work lists often come from files, folders or web pages.

See also: The walrus operator in while loops.

Your turn

Start with "main" in a work list. Print every folder in the order it is opened, oldest first.

folders = {
    "main": ["docs", "games"],
    "docs": ["notes"],
    "games": [],
    "notes": [],
}
to_open = ["main"]
# add a while loop: pop the first folder, print it, add its subfolders

Expected output

main
docs
games
notes