How to iterate in a cartesian product of lists

10,076

Solution 1

You want to use the product of the lists:

from itertools import product

for word, letter, hours in product(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):

Demo:

>>> from itertools import product
>>> for word, letter, hours in product(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):
...     print word, letter, hours
... 
AAA M 00:00
AAA M 01:00
AAA M 02:00
AAA M 03:00
...
CCC B 00:00
CCC B 01:00
CCC B 02:00
CCC B 03:00

Solution 2

Use itertools.product:

import itertools

for x in itertools.product(["AAA", "BBB", "CCC"],
                           ["M", "Q", "S", "K", "B"],
                           ["00:00", "01:00", "02:00", "03:00"]):
    print x

output:

('AAA', 'M', '00:00')
('AAA', 'M', '01:00')
...
('CCC', 'B', '02:00')
('CCC', 'B', '03:00')
Share:
10,076
alwbtc
Author by

alwbtc

Updated on June 21, 2022

Comments

  • alwbtc
    alwbtc almost 2 years

    I would like to iterate in a for loop using 3 (or any number of) lists with any number of elements, for example:

    from itertools import izip
    for x in izip(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):
        print x
    

    but it gives me:

    ('AAA', 'M', '00:00')
    ('BBB', 'Q', '01:00')
    ('CCC', 'S', '02:00')
    

    I want:

    ('AAA', 'M', '00:00')
    ('AAA', 'M', '01:00')
    ('AAA', 'M', '02:00')
    .
    .
    
    ('CCC', 'B', '03:00')
    

    Actually I want this:

    for word, letter, hours in [cartesian product of 3 lists above]
        if myfunction(word,letter,hours):
           var_word_letter_hours += 1
    
  • user4815162342
    user4815162342 almost 6 years
    This solution makes more sense if you need additional processing at different loop levels. However, the OP just wants to iterate over the triples, which with this approach must be constructed manually. Nested for loops is that they add as much indentation as there are lists, which can be a real issue for readability.
  • FinanceGuyThatCantCode
    FinanceGuyThatCantCode over 4 years
    This is also no good if the number of nested loops is not known at compile time (or whatever you want to call compile time in python)
  • Arthur Tacca
    Arthur Tacca over 4 years
    @FinanceGuyThatCantCode I already explicitly mentioned that in my answer, where I said it would be no good "if you have an arbitrary list of lists that you want to take the Cartesian product of"