Skip to main content

Loop Through a List

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

Example

Print the items in the list one at a time:

Prompt
Write a Python program that creates a list with three fruits: apple, banana, cherry. Loop through the list using a for loop and print each item.
Output: complete Python program

Loop Through the Index Numbers

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

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

Example

Use each index number to print its item:

Prompt
Write a Python program that creates a list with three fruits: apple, banana, cherry. Loop through the list items by referring to their index numbers using range() and len(), and print each item.
Output: complete Python program

Using a While Loop

A while loop can do the job too.

Get the list'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
Write a Python program that creates a list with three fruits: apple, banana, cherry. Use a while loop to go through all index numbers and print each item. Remember to increase the index by 1 after each iteration.
Output: complete Python program

Looping Using List Comprehension

For looping over a list, nothing is shorter to write than list comprehension.

Example

A compact for loop that prints every item:

Prompt
Write a Python program that creates a list with three fruits: apple, banana, cherry. Use list comprehension as a short hand for loop to print all items in the list.
Output: complete Python program