Search notes:

Python: statement for

for elem in seq:
    doSomethingWith(elem)

Iterating over a comma separated list of items

Because a string is an iterable, for allows to iterate over each character in a string:
for elem in 'foo', 42, 'bar', int:
    print(elem)
#
# foo
# 42
# bar
# <class 'int'>
Github repository about-python, path: /statements/for/in-comma-separated.py

Iterating over a list

Similarly, the for in statement allows to iterate over a list.
Unlike in Perl's foreach statement, the iteration-variable is not aliased to the elements in the list being iterated over.
#!/usr/bin/python3

lst = ['foo', 'bar', 'baz']

for elm in lst:
 #  elm is not aliased to the element in the list.
 #  Thus, the following statement does not change the
 #  list:
    elm += '!'
    print(elm)


  # checking assertion that list
  # was not changed by the += operater:
for elm in lst:
    print(elm)
Github repository about-python, path: /statements/for/in-list.py
The for x in someList construct is also used in list comprehensions.

Iterating over a numeric range

The for statement also allows to iterate over a given numeric range.
for i in range(5):
    print('  ' + str(i))
Github repository about-python, path: /statements/for/iterate-over-numeric-range.py
The previous script prints
  0
  1
  2
  3
  4
See also the built in function range.

Getting the indexes of a list when iterating over it

Sometimes, it is useful to have the index of an item in a list in addition to the item's value when iterating over the list.
This is possible by using the built-in function enumerate():
things = [ 'foo', 'bar', 'baz' ]

for item in things:
    print(item)
#    
#  foo
#  bar
#  baz

for index, item in enumerate(things):
    print(index, item)
#
#  0 foo
#  1 bar
#  2 baz
Github repository about-python, path: /statements/for/enumerate.py

Iterating over multiple lists in parallel

With zip(list_1, list_2, … list_n), it is possible to iterate over multiple lists in parallel:
list_en = [ 'one' , 'two' , 'three', 'four'   ]
list_es = [ 'un'  , 'dos' , 'tres' , 'cuatro' ]
list_de = [ 'eins', 'zwei', 'drei' , 'vier'   ]

for word_en, word_es, word_de in zip(list_en, list_es, list_de):
    print(f' {word_en:5}  {word_es:6}  {word_de}')
#
#   one    un      eins
#   two    dos     zwei
#   three  tres    drei
#   four   cuatro  vier
Github repository about-python, path: /statements/for/zip.py

Iterating over the characters of a string

Because a str (string) is also an iterable(?), the for statement allows to iterate over the characters of a string:
for character in 'hello world':
    print('  ' + character)
Github repository about-python, path: /statements/for/iterate-over-characters.py

The variable is not local to the loop

A variable that is declared in a for statement is accessible after the loop has finished and retains its last value.
This is demonstrated with this script:
for i in range(3):
    print('i = {}'.format(i))

print('Value of i after the loop: {}'.format(i))
Github repository about-python, path: /statements/for/variable-not-local-to-loop.py
When run, it prints
i = 0
i = 1
i = 2
Value of i after the loop: 2

Exiting a for-loop prematurely

A for loop can be exited at any time with the break statement.
for word in ['one', 'two', 'three', 'four', 'five', 'six']:
    if word == 'four':
       break

    print(word)
Github repository about-python, path: /statements/for/break.py
This script prints:
one
two
three

else clause

A for loop can have an else clause which is executed if the for loop is not terminated with a break or statement. Thus, the else clause can be interpreted as do this if loop successfully completed.
for i in range(1, 5):

    print('i = ' + str(i))

    for j in range(1, 3):


        print('  j = ' + str(j))
        if i == j:
           print('  i == j, breaking')
           break


    else:
        print('else reached, i = {}, j = {}'.format(i, j))
#
# i = 1
#   j = 1
#   i == j, breaking
# i = 2
#   j = 1
#   j = 2
#   i == j, breaking
# i = 3
#   j = 1
#   j = 2
# else reached, i = 3, j = 2
# i = 4
#   j = 1
#   j = 2
# else reached, i = 4, j = 2
Github repository about-python, path: /statements/for/else.py

See also

The else clause
Iterable unpacking in a for … in loop.
statements

Index