Nesting Loops in Loops

The block of statements inside a loop can contain another loop. In this code, the inner loop is executed once for each item of list outer:

 >>>​​ ​​outer​​ ​​=​​ ​​[​​'Li'​​,​​ ​​'Na'​​,​​ ​​'K'​​]
 >>>​​ ​​inner​​ ​​=​​ ​​[​​'F'​​,​​ ​​'Cl'​​,​​ ​​'Br'​​]
 >>>​​ ​​for​​ ​​metal​​ ​​in​​ ​​outer:
 ...​​ ​​for​​ ​​halogen​​ ​​in​​ ​​inner:
 ...​​ ​​print(metal​​ ​​+​​ ​​halogen)
 ...
 ...
 LiF
 LiCl
 LiBr
 NaF
 NaCl
 NaBr
 KF
 KCl
 KBr

The number of times that function print is called is len(outer) * len(inner). In Table 12, Nested Loops Over Inner and Outer Lists , we show that for each iteration of the outer loop (that is, for each item in outer), the inner loop executes three times (once per item in ...

Get Practical Programming, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.