The unofficial CircuitPython Reference

for

description

The for keyword, like while, creates loops. For is always coupled with the in keyword like this:

for someVariable in someList:
    
code block

This syntax essentially allows someVarible to sequentially take on the value of each member contained in someList and do some operations with the value by executing an indented code block below the for statement and repeating again with each value in the list in sequence.

For loops in Python, therefore operate by explicitly iterating over the members of objects that contain countable numbers of values. A countable collection in Python is called an iterator which is defined as an object that contains a countable number of values. The countable nature of an iterable Python object allows for the creation of an iterator with the iter() method which allows the interpreter to act sequentially on the iterable object's members. This is known as "iterating over a list."

The for loop will run its nested code block repeatedly, cycling through each item in an iterable collection. In Python for loops can be written for any collection of values including a list [a, b, c], tuple (a, b, c), set {"a", "b", "c"}, or dictionary {"a" : "a", "b" : "b", "c", "c"}. Ranges of values generated by the builtin range() function are also iterable as are string objects because they exist as lists of characters.

syntax

simple for loop:

for someVariable in someList:
    
code block

for loop with else:

for someVariable in someList:
    
code block
else:
    code block

methods

parameters

someVariable : A variable name specific to the for loop. Does not need to be initialized before the for statement.

someList : Any iterable Python object (object must have an iter() method associated with it). Most commonly:  list [a, b, c], tuple (a, b, c), set {"a", "b", "c"}, dictionary {"a" : "a", "b" : "b", "c", "c"}, range of values generated by range() function, or a string object.

code block : Block of code executed for each member of someList

else: An optional else statement that is executed after iterating over all members of someList

returns

Executed block of code for each member of someList

example code

serial output:


see also: