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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.