Link Search Menu Expand Document

For Loops

Table of contents

  1. Description
  2. Composition
  3. Examples
    1. Items in a container
    2. Range function
  4. Enumerate

Description

For loops are used to execute a block of code a specific number of times, or for each element of a container (such as characters in a string or objects in a list). It will only execute a finite amount of times, no more and no less.

Composition

This loop always begins with the for keyword, followed by an arbitrary variable name(s). This is followed by the in keyword, and either a pre-defined container variable (string, list, set, etc) -or- the range function:

for loop_variable in range(15):
    # this code block executes the specific number of times indicated in the range function argument

for loop_variable in container_variable:
    # this code block executes for each item in the container variable

Examples

Items in a container

The program illustrated below will execute for each item in the flavors list. Therefore, it will execute exactly four times, since there are four items in the list:

With each new iteration of the loop, the next item in the list is assigned to the loop variable before the code block is executed. The loop will end once each element in the flavors list has been assigned to the loop variable:

Range function

The program illustrated below will execute the number of times specified in the range function. In this example, that is exactly five times:

With each new iteration of the loop, the next number from the range function is stored in the loop variable before the code block is executed. The loop will end execution once it has executed the specific number of times indicated in the range function:

Enumerate

Applying the enumerate function to a for loop adds a number to each item in the container. In order to “catch” this additional value, you add a second loop variable to the for loop. The enumerate function combined with a for loop is commonly used to store the index number of each item:

With each new iteration of the for loop, the first loop variable is assigned an incrementing number beginning with zero. The second loop variable is assigned the value of the next element of the container: