How to loop over an array in Python?

You can use a for in loop to get the elements of the array.

colours = ["red","green","blue"]
 
for colour in colours:
    print colour
 
# red
# green
# blue

However if you also need access to the position of the element in the array we can use a for in loop over a range

colours = ["red","green","blue"]
 
for i in range(0, len(colours)):
    print i, colour[i]
 
# 0 red
# 1 green
# 2 blue
You can leave a response, or trackback from your own site.

2 Responses to “How to loop over an array in Python?”

  1. Mythmon says:

    Instead of the example with range, you could do this

    for i, colour in enumerate(colours):
    print i, colour

  2. trips says:

    shouldn’t it be

    print i, colours[i]

    instead of
    print i, colour[i]

Leave a Reply