How to use the Python for loop

Nancy J. Delong

When you want to create a loop in Python, you generally have two choices: the when loop and the for loop. when is easy: it just repeats until eventually a offered ailment is no longer genuine. The for loop is a lot more elaborate, and so a lot more potent: for lets you iterate by way of objects in a collection of some form without having to know particulars about the collection.

Python for loop factors

A Python for loop has two factors:

  • A container, sequence, or generator that includes or yields the components to be looped in excess of. In general, any object that supports Python’s iterator protocol can be employed in a for loop.
  • A variable that retains each individual component from the container/sequence/generator.

In the pursuing case in point, we loop by way of a listing of numbers, and use the variable digit to hold each individual number in change:

for digit in [3,one,4,one,5,9]:
    print (digit)

This will print:


If you are iterating by way of an object that yields containers or sequences, you can use Python’s multi-assignment syntax to unpack them. For instance:

for letter, number in [["a",one],["b",two]]:
    print (letter, number)

The output:

a one
b two

Common Python for loops

Listed here are some prevalent objects employed in a Python for loop:


The case in point earlier mentioned shows how a listing can be iterated in excess of working with a for loop. Take note that if you have a listing of lists, each individual component extracted by the for loop will alone be a listing. for loops do not instantly “flatten” nested constructions of any form.


Strings in Python are regarded as “sequences” — they can be iterated in excess of, and the benefits of iterating in excess of a string are each individual character in the string.

for letter in "Hello environment":
    print (letter)

This would produce:




Iterating by way of a dictionary with a for loop yields each individual key in the dictionary.

d1 = 
    "a": one,
    "b": two

for key in d1:
    print (key)

This would produce:


If you want to iterate by way of the values of a dictionary, use the dictionary’s .values() method. You can also iterate by way of keys and values together, with .things():

d1 = 
    "a": one,
    "b": two

for key, worth in d1.things():
    print (key, worth)

This would produce:

a one
b two


Generators produce a succession of things, one particular for each individual time they are named. A prevalent case in point of a generator employed in a for loop is vary.

for n in vary(50):
    print (n)

This would print the numbers by way of 49.

Take note that just mainly because you can use a generator in a for loop does not mean that the generator will eventually halt of its very own accord. For instance, this for loop will operate eternally:

def eternally():
    when Correct:
        produce one

for n in eternally():
    print (n)

In these circumstances you may want to take steps to be certain the loop can terminate. (See “Flow control” down below.)

Utilizing indexes and enumerate with a Python for loop

Builders who appear to Python from languages like C, C++, or Java will typically create an index variable that is employed to move by way of the object staying iterated. An case in point:

n = 
when n

This is not completely wrong as these, but it misses the issue of how Python works. A for loop in Python does not demand an index it can just traverse the object to be iterated in excess of without needing to index into it.

Even so, in some cases you need to have to maintain keep track of of which component you are dealing with when looping. Python’s enumerate() utility assists with this. It normally takes an iterable and on each individual iteration generates a tuple of the index and the object at that index:

x = [3,one,4,one,5,9]
for index, n in enumerate(x):
    print (index, n)
one one
two 4 
3 one
4 5
5 9

Flow control in a Python for loop

for loops never generally operate to completion, or in specific sequence. Occasionally you want to depart a for loop early, or skip in excess of an product in the loop. To do that, Python gives you with two keywords and phrases: split and proceed.

for n in vary(twenty):
    if n % two == : # if n is a multiple of two
        proceed   # then skip it
    # anything soon after this issue is not operate
    # if `continue` is invoked
    print (n)
print ("Completed")

This yields one 3 5 seven 9 eleven thirteen fifteen 17 19, then Completed. Take note that when the loop ends, the program proceeds generally at print ("Completed").

for n in vary(twenty):
    if n == ten:
        split # depart the loop altogether
    print (n)
print ("Completed")

This prints the numbers by way of 9, then Completed.

Take note that if you have loops nested inside of other loops, split will only influence the existing loop — it will not exit from all loop levels. Exiting from multiple for loops requires a various mechanism, like a sentinel variable:

performed = Phony
for n in vary(twenty):
    for m in vary(40):
        if n==ten and m==ten:
            performed = Correct
        if performed: split
    if performed: split

A Python for loop gotcha

When iterating in excess of the components of an object in a for loop, never do anything that would change the users or duration of the sequence. For instance, if you are iterating in excess of a listing, never add or remove components from the listing as you iterate.

If the rationale you are iterating in excess of components is to test each individual component to see if you need to have to add or remove something, there is a greater resolution. Create a new, vacant container, populate it only with the components you want to maintain, then change the aged container with the new one particular.

Listed here is an case in point with a listing. This makes a new listing that includes only odd numbers:

aged_listing = [one,two,3,4,5,6]
new_listing = []
for n in aged_listing:
    if n % two:
aged_listing = new_listing

Copyright © 2021 IDG Communications, Inc.

Next Post

Tecno Camon 17 Series Teased to Launch in India Soon, Amazon Availability Confirmed

Tecno Camon 17 series has been teased to start in India quickly. The business has detailed a committed teaser web site on Amazon, confirming its availability on the e-commerce platform as properly. The teasers counsel that the business could announce the Tecno Camon 17 Professional and Tecno Camon 17 telephones […]