Prev: - Break, continue, pass       |       Next: range

# 'for' loop¶

## for¶

• 'for' loop is an important programming command in Python as it implements some key ideas and constructs of the language
• The general syntax of the 'for' loop is:
In [ ]:
for iterator in iterable:
block-1
else:
block-2


## iterable¶

• The power engine in the 'for' loop is always an iterable object
• Generally speaking, an iterable is any object that returns a sequence of values, one by one, to the iterator variable. For each new value returned, a new for-loop iteration is executed. When the value sequence ends, the loop execution is over.
• More technically speaking, an iterable object is an object possessing a __next__ method, which returns the next in sequence item of the iterable object each time it is called.
• The iterator variable is simply a name bound to the value returned by the iterable.

See an example:

In [1]:
# a simple example with the list [1,2,3,4,5] as iterable

asum = 0

for i in [1,2,3,4,5]:
asum += i
print(i, asum)

print('for loop is now over')

1 1
2 3
3 6
4 10
5 15
for loop is now over

• Consider carefully the following:
• The list [1,2,3,4,5] is used as an iterable in this example.
• The values [1,2,3,4,5] are returned (that is: assigned one-by-one) to the iterator variable 'i'.
• In each iteration the variable asum is increased by adding the current value of i in the running iteration
• The for loop is iterrated over five times (as many as the values of the iterable list returned). After the sequence of values is exhausted the for loop ends also automatically.

Lists will be thoroughly discussed in next sections. A simple list is used in this introductory example as it provides a nice visualization of a sequence of values, returned one-by-one to the itetrator

## 'for' examples with various iterables¶

• The power of the for loop comes from the fact that in Python there are many iterable objects that can be used to make a for loop operational.
• Strings and List of strings are two such objects in the following examples:
In [2]:
for i in ['spam','eggs','ham']:      # List of strings as iterable object in the loop
print(i, end=' ')

print('\n')

m = 'spam'
for ch in m:      # String as iterable object
print(ch)


spam eggs ham

s
p
a
m

In [3]:
# In the following examples try first to guess the print() outcomes..
#.. and then run the code to assess your understanding

alist = ['a','b','c','d','e']
ch = ''
for i in alist:
ch += i
print(ch)

abcde

In [4]:
v = 0
for b in [True, False]:
v +=1
if b:
print(v)
print(v)

1
2

In [5]:
alist = ['a','b','c']
i = 0
s=''
for ch in alist:
i +=2
s = s+i*ch
print(s)

aabbbbcccccc

In [6]:
# multiplication table
# Python convention: Constant values are written with capital letters
# 'Constant' means that the programmer will not change these values during code execution
MIN = 1
MAX = 10

for i in range(MIN, MAX+1):
for j in range(MIN, MAX+1):
print('\t', i*j, end='')  # try both prints and observe the difference
#print('{:8d}'.format(i*j), end='')
print()

	 1	 2	 3	 4	 5	 6	 7	 8	 9	 10
2	 4	 6	 8	 10	 12	 14	 16	 18	 20
3	 6	 9	 12	 15	 18	 21	 24	 27	 30
4	 8	 12	 16	 20	 24	 28	 32	 36	 40
5	 10	 15	 20	 25	 30	 35	 40	 45	 50
6	 12	 18	 24	 30	 36	 42	 48	 54	 60
7	 14	 21	 28	 35	 42	 49	 56	 63	 70
8	 16	 24	 32	 40	 48	 56	 64	 72	 80
9	 18	 27	 36	 45	 54	 63	 72	 81	 90
10	 20	 30	 40	 50	 60	 70	 80	 90	 100


## the 'else' branch - break, continue & pass¶

• An 'else' branch is optional in a for loop. However, if there is one it is only executed once after all iterations are completed
• The break, continue and pass operate in the usual manner as explained in the 'while' section
In [7]:
totalsum = evensum = 0

for i in range(1,11):
totalsum += i
if i%2: continue
evensum += i
else:
print(totalsum, evensum)

print('for loop is now over')

55 30
for loop is now over


. Free learning material
. See full copyright and disclaimer notice