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)
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
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