Looping Through Lists in Python: How to Iterate Over List Items

Learn how to loop through items in a Python list using a for loop. This guide provides a clear example of printing each item in a list, one by one. Discover how to efficiently iterate over list elements and handle data in your Python programs.



Python - Loop Lists

Loop Through a List

You can loop through the items in a list by using a for loop:

Example

Print all items in the list, one by one:


mylist = ["dog", "cat", "bird"]
for x in mylist:
    print(x)
Output

dog
cat
bird

Learn more about for loops in our Python For Loops Chapter.

Loop Through the Index Numbers

You can also loop through the items in a list by referring to their index numbers.

Use the range() and len() functions to create a suitable iterable.

Example

Print all items by referring to their index numbers:


fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
    if "a" in x:
        newlist.append(x)

print(newlist)
Output

["apple", "banana", "mango"]

The iterable created in the example above is [0, 1, 2].

Using a While Loop

You can loop through the items in a list by using a while loop.

Use the len() function to determine the length of the list, then start at 0 and loop through the list items by referring to their indexes.

Remember to increase the index by 1 after each iteration.

Example

Print all items, using a while loop to go through all the index numbers:


mylist = ["dog", "cat", "bird"]
i = 0
while i < len(mylist):
    print(mylist[i])
    i = i + 1
Output

dog
cat
bird

Learn more about while loops in our Python While Loops Chapter.

Looping Using List Comprehension

List Comprehension offers a shorter syntax for looping through lists:

Example

A shorthand for loop that prints all items in a list:

Example

mylist = ["dog", "cat", "bird"]
[print(x) for x in mylist]
Output

dog
cat
bird

Learn more about list comprehension in the next chapter: List Comprehension.