How to use the Python for loop

Victoria D. Doty

When you want to generate a loop in Python, you typically have two selections: the whilst loop and the for loop. whilst is straightforward: it just repeats right until a offered ailment is no longer correct. The for loop is extra sophisticated, and as a result extra impressive: for lets you iterate via objects in a selection of some type with out acquiring to know details about the selection.

Python for loop components

A Python for loop has two components:

  • A container, sequence, or generator that has or yields the factors to be looped over. In common, any item that supports Python’s iterator protocol can be employed in a for loop.
  • A variable that holds every ingredient from the container/sequence/generator.

In the pursuing illustration, we loop via a listing of numbers, and use the variable digit to maintain every number in flip:

for digit in [3,1,four,1,five,9]:
    print (digit)

This will print:


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

for letter, number in [["a",1],["b",2]]:
    print (letter, number)

The output:

a 1
b 2

Widespread Python for loops

Right here are some widespread objects employed in a Python for loop:


The illustration above shows how a listing can be iterated over working with a for loop. Note that if you have a listing of lists, every ingredient extracted by the for loop will alone be a listing. for loops do not automatically “flatten” nested buildings of any type.


Strings in Python are viewed as “sequences” — they can be iterated over, and the benefits of iterating over a string are every character in the string.

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

This would generate:




Iterating via a dictionary with a for loop yields every important in the dictionary.

d1 = 
    "a": 1,
    "b": 2

for important in d1:
    print (important)

This would generate:


If you want to iterate via the values of a dictionary, use the dictionary’s .values() technique. You can also iterate via keys and values with each other, with .objects():

d1 = 
    "a": 1,
    "b": 2

for important, benefit in d1.objects():
    print (important, benefit)

This would generate:

a 1
b 2


Turbines generate a succession of objects, just one for every time they are identified as. A widespread illustration of a generator employed in a for loop is assortment.

for n in assortment(fifty):
    print (n)

This would print the numbers via forty nine.

Note that just simply because you can use a generator in a for loop doesn’t imply that the generator will inevitably end of its individual accord. For instance, this for loop will run for good:

def for good():
    whilst Legitimate:
        generate 1

for n in for good():
    print (n)

In these conditions you may perhaps want to get methods to assure the loop can terminate. (See “Flow control” beneath.)

Applying indexes and enumerate with a Python for loop

Builders who occur to Python from languages like C, C++, or Java will normally generate an index variable that is employed to step via the item getting iterated. An illustration:

n = 
whilst n

This isn’t incorrect as these, but it misses the stage of how Python functions. A for loop in Python doesn’t call for an index it can just traverse the item to be iterated over with out needing to index into it.

Nonetheless, occasionally you have to have to keep monitor of which ingredient you’re dealing with whilst looping. Python’s enumerate() utility aids with this. It can take an iterable and upon every iteration generates a tuple of the index and the item at that index:

x = [3,1,four,1,five,9]
for index, n in enumerate(x):
    print (index, n)
1 1
2 four 
3 1
four five
five 9

Circulation command in a Python for loop

for loops don’t normally run to completion, or in precise sequence. Sometimes you want to leave a for loop early, or skip over an merchandise in the loop. To do that, Python delivers you with two search phrases: crack and carry on.

for n in assortment(20):
    if n {394cb916d3e8c50723a7ff83328825b5c7d74cb046532de54bc18278d633572f} 2 == : # if n is a multiple of 2
        carry on   # then skip it
    # almost everything soon after this stage is not run
    # if `continue` is invoked
    print (n)
print ("Carried out")

This yields 1 3 five 7 9 eleven 13 fifteen seventeen 19, then Carried out. Note that when the loop finishes, the software carries on usually at print ("Carried out").

for n in assortment(20):
    if n == 10:
        crack # leave the loop entirely
    print (n)
print ("Carried out")

This prints the numbers via 9, then Carried out.

Note that if you have loops nested inside other loops, crack will only have an impact on the latest loop — it would not exit from all loop levels. Exiting from multiple for loops necessitates a unique system, like a sentinel variable:

carried out = Bogus
for n in assortment(20):
    for m in assortment(40):
        if n==10 and m==10:
            carried out = Legitimate
        if carried out: crack
    if carried out: crack

A Python for loop gotcha

When iterating over the factors of an item in a for loop, don’t do just about anything that would change the users or size of the sequence. For instance, if you’re iterating over a listing, don’t include or remove factors from the listing as you iterate.

If the reason you’re iterating over factors is to test every ingredient to see if you have to have to include or remove something, there is a better alternative. Produce a new, vacant container, populate it only with the factors you want to keep, then swap the previous container with the new just one.

Right here is an illustration with a listing. This creates a new listing that has only odd numbers:

previous_listing = [1,2,3,four,five,six]
new_listing = []
for n in previous_listing:
    if n {394cb916d3e8c50723a7ff83328825b5c7d74cb046532de54bc18278d633572f} 2:
previous_listing = new_listing

Copyright © 2021 IDG Communications, Inc.

Next Post

Everything You Ever Wanted to Know About Tabletop RPGs

Shannon Appelcline’s four-guide collection Designers and Dragons provides an extremely specific look at the record of tabletop roleplaying online games, featuring profiles of more than a hundred firms, like TSR, Wizards of the Coastline, and White Wolf. “The scale of the task was certainly huge, and the only way that it […]

Subscribe US Now