Python Language


Loops All Versions

Python 2.x

2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7

Python 3.x

3.0
3.1
3.2
3.3
3.4
3.5
3.6

This draft deletes the entire topic.

Introduction

As one of the most basic functions in programming, loops are an important piece to nearly every programming language. Loops enable developers to set certain portions of their code to repeat through a number of loops which are referred to as iterations. This topic covers using multiple types of loops and applications of loops in Python.

expand all collapse all

Examples

  • 17

    break statement

    When a break statement executes inside a loop, control flow "breaks" out of the loop immediately:

    i = 0
    while i < 7:
        print(i)
        if i == 4:
            print("Breaking from loop")
            break
        i += 1
    

    The loop conditional will not be evaluated after the break statement is executed. Note that break statements are only allowed inside loops, syntactically. A break statement inside a function cannot be used to terminate loops that called that function.

    Executing the following prints every digit until number 4 when the break statement is met and the loop stops:

    0
    1
    2
    3
    4
    Breaking from loop
    

    break statements can also be used inside for loops, the other looping construct provided by Python:

    for i in (0, 1, 2, 3, 4):
        print(i)
        if i == 2:
            break
    

    Executing this loop now prints:

    0
    1
    2
    

    Note that 3 and 4 are not printed since the loop has ended.

    If a loop has an else clause, it does not execute when the loop is terminated through a break statement.

    continue statement

    A continue statement will skip to the next iteration of the loop bypassing the rest of the current block but continuing the loop. As with break, continue can only appear inside loops:

    for i in (0, 1, 2, 3, 4, 5):
        if i == 2 or i == 4:
            continue
        print(i)
    
    0
    1
    3
    5
    

    Note that 2 and 4 aren't printed, this is because continue goes to the next iteration instead of continuing on to print(i) when i == 2 or i == 4.

    Nested Loops

    break and continue only operate on a single level of loop. The following example will only break out of the inner for loop, not the outer while loop:

    while True:
        for i in range(1,5):
            if i == 2:
                break    # Will only break out of the inner loop!
    

    Python doesn't have the ability to break out of multiple levels of loop at once -- if this behavior is desired, refactoring one or more loops into a function and replacing break with return may be the way to go.

    Use return from within a function as a break

    The return statement exits from a function, without executing the code that comes after it.

    If you have a loop inside a function, using return from inside that loop is equivalent to having a break as the rest of the code of the loop is not executed (note that any code after the loop is not executed either):

    def break_loop():
        for i in range(1, 5):
            if (i == 2):
                return(i)
            print(i)
        return(5)
    

    If you have nested loops, the return statement will break all loops:

    def break_all():
        for j in range(1, 5):
            for i in range(1,4):
                if i*j == 6:
                    return(i)
                print(i*j)
    

    will output:

    1 # 1*1
    2 # 1*2
    3 # 1*3
    4 # 1*4
    2 # 2*1
    4 # 2*2
    # return because 2*3 = 6, the remaining iterations of both loops are not executed
    
  • 10

    for loops iterate over a collection of items, such as list or dict, and run a block of code with each element from the collection.

    for i in [0, 1, 2, 3, 4]:
        print(i)
    

    The above for loop iterates over a list of numbers.

    Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, etc. The output will be as follow:

    0  
    1
    2
    3
    4
    

    range is a function that returns a series of numbers under an iterable form, thus it can be used in for loops:

    for i in range(5):
        print(i)
    

    gives the exact same result as the first for loop. Note that 5 is not printed as the range here is the first five numbers counting from 0.

    Iterable objects and iterators

    for loop can iterate on any iterable object which is an object which defines a __getitem__ or a __iter__ function. The __iter__ function returns an iterator, which is an object with a next function that is used to access the next element of the iterable.

  • 6

    To iterate through a list you can use for:

    for x in ['one', 'two', 'three', 'four']:
        print(x)
    

    This will print out the elements of the list:

    one
    two
    three
    four
    

    Generated numbers using range is also gives a list as an output.

    for x in xrange(1, 6):
        print(x)
    

    Result will not be in a list.

    1
    2
    3
    4
    5
    

    If you want to loop though both the elements of a list and have an index for the elements as well, you can use python's excellent enumerate function:

    for index, item in enumerate(['one', 'two', 'three', 'four']):
        print(index, '::', item)
    

    enumerate will generate tuples, which are unpacked into index (an integer) and item (the actual value from the list). The above loop will print

    (0, '::', 'one')
    (1, '::', 'two')
    (2, '::', 'three')
    (3, '::', 'four')
    

    Iterate over a list with value manipulation using map and lambda, i.e. apply lambda function on each element in the list:

    x = map(lambda e :  e.upper(), ['one', 'two', 'three', 'four'])
    print(x)
    

    Output:

    ['ONE', 'TWO', 'THREE', 'FOUR'] # python 2.x
    

    NB: in Python 3.x map returns an iterator instead of a list so you in case you need a list you have to cast the result print(list(x)).

Please consider making a request to improve this example.

Syntax

  • while <boolean expression>:
  • for <variable> in <iterable>:
  • for <variable> in range(<number>):
  • for <variable> in range(<start_number>, <end_number>):
  • for i, <variable> in enumerate(<iterable>): # with index i
  • for <variable1>, <variable2> in zip(<iterable1>, <iterable2>):

Parameters

ParameterDetails
boolean expressionexpression that can be evaluated in a boolean context, e.g. x < 10
variablevariable name for the current element from the iterable
iterableanything that implements iterations

Remarks

Remarks

Still have a question about Loops? Ask Question

Topic Outline