Iterate a list in Python

In today’s example we are going to iterate a list in Python. The first thing we will do is define a list, then go through all the elements it contains and display them on the screen.

The first thing will be to define the list in Python:

list = ["carmen","elena","lucia","sara","patricia","sonsoles"]

The list is defined by a set of elements that are delimited by square brackets ([ ]) and are in turn separated by commas.

Once we have defined the list, the next thing will be to iterate the list in Python. For this we are going to use a for-each statement. The structure of the iterative for-each statement is as follows:

for variable in list:
  # Actions

In each of the iterations on the elements of the list the variable will be the one that contains the element of the list.

In this way, using the list defined at the beginning, our for-each loop helps us to iterate a list in Python will look like this:

print "Loop through list with a foreach"
for element in list:
    print element

In this way the screen output will be:

Traverse list with a foreach
carmen
elena
lucia
sarah
patricia
sonsoles

I hope this example that teaches us how to iterate a list in Python.

Leave a Comment