Python - For loop

By xngo on June 14, 2019

In Python, a for loop is used to iterate over the members of a sequence. Here are some examples,

animals = [ 'cat', 'dog', 'hamster' ]
 
# Looping through a list.
for item in animals:
    print(item)
 
# Looping through a list using range().
for i in range(0, len(animals)):
    print(animals[i])
 
# Looping through a string.
for letter in "hamster":
    print(letter)

Break statement

With the break statement, you can stop the loop before it has looped through all the items.

animals = [ 'cat', 'dog', 'hamster' ]
# Stop looping when item is equal to dog.
for item in animals:
    if item == 'dog':
        break
    print(item)

Continue statement

With the continue statement, you can skip the current iteration and go to the next iteration.

animals = [ 'cat', 'dog', 'hamster' ]
# Skip displaying dog.
for item in animals:
    if item == 'dog':
        continue
    print(item)

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.