0

I would like to replace this nested loop with itertools.product:

seasons = ['long', 'short']
weathers = ['dry', 'wet', 'sunny']

for season in seasons:
    for weather in weathers:
        output = "S= " + season + "&" + "W= " + weather
        print(output)

Output

S= long&W= dry
S= long&W= wet
S= long&W= sunny
S= short&W= dry
S= short&W= wet
S= short&W= sunny

I know I can print all elements using this:

mylist = list([seasons, weathers])
for element in itertools.product(*mylist):
    print(element)

But how can I call individual elements within itertools.product?

Ali
  • 1,048
  • 8
  • 19
  • 1
    I don't understand what you are asking. Aren't you printing individual elements in your last example? Maybe you should show a small example of what exactly you want to achieve. – mkrieger1 Dec 23 '20 at 20:45
  • I would like to achieve the same output but with the `itertools.product` instead of a nested for loop. – Ali Dec 23 '20 at 20:45
  • Yes, it does. Thank you. – Ali Dec 23 '20 at 20:59

1 Answers1

1

You can use two variables in the for loop (to unpack the tuple returned by product):

from itertools import product

seasons = ['long', 'short']
weathers = ['dry', 'wet', 'sunny']

for season, weather in product(seasons, weathers):
    output = "S= " + season + "&" + "W= " + weather
    print(output)

Output:

S= long&W= dry
S= long&W= wet
S= long&W= sunny
S= short&W= dry
S= short&W= wet
S= short&W= sunny
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 2
    Note: This is the way you *should* use `product` in this scenario, and how it's intended to be used. Like a lot of `itertools` module stuff that produces `tuple`s (and like `zip`), it has an optimized fast path for when the `tuple` it returns is unused when the output is requested; by unpacking, you release the `tuple` immediately, so the fast path can be used. – ShadowRanger Dec 23 '20 at 20:50
  • 1
    That should read: "when the *next* output is requested", and of course I only noticed this after the edit grace period expired. – ShadowRanger Dec 23 '20 at 21:01