Better method to iterate over 3 lists

You can use itertools.product to get the product of your width and height, that is your whole grid. Then, you want to cycle over the keys, thus use itertools.cycle. You finally zip those together and get the desired result.

You can make this a generator using yield for memory efficieny.

from itertools import product, cycle

def get_grid(width, height, keys):
    for pos, key in zip(product(width, height), cycle(keys)):
        yield (*pos, key)

Or if you do not want a generator.

out = [(*pos, key) for pos, key in zip(product(width, height), cycle(keys))]

Example

width = [0,1,2,3,4,6,7,8,9]
height = [0,1,2,3,4]
keys = [18,20,11]

for triple in get_grid(width, height, keys):
    print(triple)

Output

(0, 0, 18)
(0, 1, 20)
(0, 2, 11)
(0, 3, 18)
(0, 4, 20)
(1, 0, 11)
(1, 1, 18)
...

As a sidenote, notice that you could replace the lists defining width and height by ranges.

width = range(10)
height = range(5)

Tags:

Python