🎓 A1Learner
🔍

Python Loop Lists

Looping a list visits each item in the list, one at a time.

Loop over the items

The loop variable takes each item in turn.

prices = [10, 25, 4]
for price in prices:
    print(price)

Loop over the indexes

range(len(names)) gives 0, 1, and 2. Use the index to fetch each item.

names = ["Ada", "Ben", "Cid"]
for i in range(len(names)):
    print(i, names[i])

Loop with while

A counter starts at 0. The loop stops when the counter reaches the list length.

names = ["Ada", "Ben", "Cid"]
i = 0
while i < len(names):
    print(names[i])
    i = i + 1

Example

prices = [50, 20, 12, 8]
for number, price in enumerate(prices, start=1):
    new_price = price * 0.9
    print(number, price, "->", new_price)

Key points

  • Use for item in my_list to visit each item in order
  • Use for i in range(len(my_list)) when you also need the index
  • A while loop over a list needs a counter variable
  • You must move the counter yourself.
  • Pick the simple for loop by default
  • Reach for an index loop only when the index matters.
  • Build a new list instead.

In this example, enumerate() gives each price with a number, starting at 1. The loop runs once for each of the four prices. new_price works out a 10% discount by multiplying by 0.9. Each print shows the number, the old price, and the new price.

Note

Do not add or remove items while a for loop walks the same list, because Python can skip items that way.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does this code print? nums = [2, 4, 6] for n in nums: print(n * 10)