June 2018
Beginner
508 pages
13h 8m
English
Let's see an example of nested loops. It's very common when dealing with algorithms to have to iterate on a sequence using two placeholders. The first one runs through the whole sequence, left to right. The second one as well, but it starts from the first one, instead of 0. The concept is that of testing all pairs without duplication. Let's see the classical for loop equivalent:
# pairs.for.loop.pyitems = 'ABCD'pairs = []for a in range(len(items)): for b in range(a, len(items)): pairs.append((items[a], items[b]))
If you print pairs at the end, you get:
$ python pairs.for.loop.py[('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'C'), ('C', 'D'), ('D', 'D')]
All the tuples with ...
Read now
Unlock full access