Skip to main content

Loop Through a Tuple

A for loop is the natural way to visit each item in a tuple.

Example

Print each value as you go through the items:

Prompt
Create a tuple with three fruits and use a for loop to iterate through the items and print each value.
Output: complete Python program

Loop Through the Index Numbers

Another option is to go through the tuple by index number.

Together, range() and len() give you a suitable iterable of indexes.

Example

Use each index number to print its item:

Prompt
Create a tuple with three fruits. Use range() and len() to loop through the tuple items by index number and print each item.
Output: complete Python program

Using a While Loop

A while loop can do the job too.

Get the tuple's length with len(), begin at index 0, and use the indexes to work through the items one after another.

Don't forget to add 1 to the index on every pass.

Example

Step through every index with a while loop and print each item:

Prompt
Create a tuple with three fruits. Use a while loop to print all items by referring to their index numbers. Remember to increase the index by 1 after each iteration.
Output: complete Python program