Python | Loops | For Loop

A for loop allows you to perform operations a number of times. It can also be used in the same way as while loop.

As a quick example let’s take a look at the following code:

days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
for name in days:
	print(name)

The for loop takes first time the value of the days[0] and assigns it to the variable name then it prints it on the screen. It does the same with all other items from the array.

If you run the code into the terminal this is what you get.

Python - for loop

Another quick example in case you work with a string:

message = 'Just a message'
for each_letter in message:
	print(each_letter)

The for loop in this case takes every single character of the string and assigns it as a value of the variable each_letter then it prints it on the screen. It does it one by one for each character.

This is what you get if you run the code in terminal:

Python - for loop

The next two examples compute the sum and product of all the items in a list.

>>> sum = 0
>>> for x in [1, 2, 3]:
...     sum = sum + x
... 
>>> sum
6

The for loops ca iterate over strings and tuples as well.

>>> S1 = 'honda'
>>> T1 = ('it', 'is', 'great')
>>> for s in S1:
...     print(s, end=' ')
... 
h o n d a >>> 
>>> for t in T1:
...     print(t, end=' ')
... 
it is great >>> 

Note:
The for loops ca iterate over files and dictionaries too.

Iterating through a sequence of tuples (the loop target itself can be a tuple of targets)

>>> T2 = [(1, 2), (3, 4), (5, 6)]
>>> for (x, y) in T2:
...     print(x, y)
... 
1 2
3 4
5 6

This form is commonly used in conjunction with the zip call to implement parallel traversals. It also makes regular appearances in conjunction with SQL databases in Python, where query result tables are returned as sequences of sequences (the outer list is the database table, the nested tuples are the rows within the table, and tuple assignment extracts columns).

Tuples in for loops can iterate through both keys and values in dictionaries using the items method.

# Use dict keys iterator and index
D1 = {'a': 1, 'b': 2, 'c': 3}
for key in D1:
	print(key, '-->', D1[key])

The output in the terminal will be:

ddn_ro@Linux:~$ python3 test.py
c --> 3
b --> 2
a --> 1

You will get the same result by iterating over keys and values.

D1 = {'a': 1, 'b': 2, 'c': 3}
list(D1.items())
for (key, value) in D1.items():
	print(key, '-->', value)

Any assignment target works syntactically after the word for.

# assign manually within the loop to unpack
D1 = {'a': 1, 'b': 2, 'c': 3}
list(D1.items())
for both in D1.items():
	a, b = both
	print(a, b)

The result in the terminal will be:

ddn_ro@Linux:~$ python3 test.py
b 2
c 3
a 1

Nested structures may be automatically unpacked in a for.

>>> ((a, b), c) = ((1, 2), 3)
>>> a, b, c
(1, 2, 3)
>>> for ((a, b), c) in [((1, 2), 3), ((4, 5), 6)]:
...     print(a, b, c)
... 
1 2 3
4 5 6

Any nested sequence structure may be unpacked this way because sequence assignment is generic.

>>> for ((a, b), c) in [([1, 2], 3), ['xy', 6]]:
...     print(a, b, c)
... 
1 2 3
x y 6

A tuple of values is assigned to a tuple of names on each iteration.

>>> x, y, z = (1, 2, 3)
>>> x, y, z
(1, 2, 3)
>>> for (x, y, z) in [(1, 2, 3), (4, 5, 6)]:
...     print(x, y, z)
... 
1 2 3
4 5 6

In Python 3.X a sequence can be assigned to a more general set of names with a starred name to collect multiple items.

x, *y, z = (1, 2, 3, 4, 5)
for (x, *y, z) in [(1, 2, 3, 4, 5), (6, 7, 8, 9, 10)]:
	print(x, y, z)

The output in the terminal will be:

ddn_ro@Linux:~$ python3 test.py
1 [2, 3, 4] 5
6 [7, 8, 9] 10

The next example illustrates statement nesting and the loop else clause in a for .
We have a list of objects (items) and a list of keys (tests). The code searches for each key in the objects list and reports on the search’s outcome.

items = ["ali", 123, (8, 9), 3.14, "Flora", "Honda"]
tests = ["Yamaha", 3.14, 8, (8, 9)]

for key in tests:
	for item in items:
		if item == key:
			print(key, "found")
			break
	else:
		print(key, "not found!")

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
Yamaha not found!
3.14 found
8 not found!
(8, 9) found

There are two loops acting at the same time. The outer loop scans the keys list, and the inner loop scans the items list for each key.

The nested if runs a break when a match is found. The loop else clause can assume that if it is reached, the search has failed.

The nesting of the loop else clause is a very important part of this code; it’s indented to the same level as the header line of the inner for loop, so it’s associated with the inner loop, not the if or the outer for.

Of course you could use the in operator to test membership and the result in the terminal will be the same.

items = ["ali", 123, (8, 9), 3.14, "Flora", "Honda"]
tests = ["Yamaha", 3.14, 8, (8, 9)]

for key in tests:
	if key in items:
		print(key, "found")
	else:
		print(key, "not found!")

In the next example a list is built for later use instead of printing.
It performs a typical data-structure task with a for (collects common items in two sequences), and serves as a rough set intersection routine. After the loop runs, res refers to a list that contains all the items found in seq1 and seq2 :

prop1 = "honda"
prop2 = "yamaha"

rez = []
for x in prop1:
	if x in prop2:
		rez.append(x)

print(rez)

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
['h', 'a']

Leave a Reply