🎓 A1Learner
🔍

Python Loop Tuples

A for loop visits each item in a tuple, one by one. A tuple loops the same way as a list.

Loop over each item

for takes each item in turn.

animals = ("cat", "dog", "fox")
for animal in animals:
    print(animal)

Loop with an index

Use this form when you need the position too.

animals = ("cat", "dog", "fox")
for i in range(len(animals)):
    print(i, animals[i])

Check with in

in gives True or False. It never changes the tuple.

fruit = ("apple", "banana")
print("banana" in fruit)
print("pear" in fruit)

Tuples inside a list

Each tuple here is one short record.

records = [("Ada", 10), ("Bob", 7)]
print(records[0])
print(records[1][0])

A list inside a tuple

A tuple can hold a list as one of its items.

team = ("Rockets", ["Ada", "Bob"])
print(team[0])
print(team[1])

Example

results = [("Ada", 12), ("Bob", 9), ("Cy", 15)]
total = 0
for player, pts in results:
    total += pts
    print(player, pts)
print("Total:", total)

Key points

  • Use for to visit each item in a tuple, one by one
  • Use range(len(...)) when you also need the index
  • Use in to check if an item is in a tuple
  • A list can hold tuples, which is handy for short records
  • Use a second pair of brackets to reach inside a nested item
  • An inner list held in a tuple can still change, even though the tuple itself cannot.

In this example, results is a list of three small tuples. Each tuple holds a player name and some points. The loop unpacks each tuple into player and pts. Each round adds pts to total and prints one line. After the loop, the code prints the total, which is 36.

Note

A tuple can hold a list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which check tells you if "fox" is in the tuple animals?