All permutations from 2 lists

Rob Cliffe rob.cliffe at btinternet.com
Tue Mar 1 19:32:46 EST 2022


I would not use `os` as an identifier, as it is the name of an important 
built-in module.
I think itertools.product is what you need.
Example program:

import itertools
opsys = ["Linux","Windows"]
region = ["us-east-1", "us-east-2"]
print(list(itertools.product(opsys, region)))

Output:

[('Linux', 'us-east-1'), ('Linux', 'us-east-2'), ('Windows', 
'us-east-1'), ('Windows', 'us-east-2')]

itertools.product returns an iterator (or iterable, I'm not sure of the 
correct technical term).
If you only want to use the result once you can write e.g.

     for ops, reg in itertools.product(opsys, region):
         etc.

If you need it more than once, you can convert it to a list (or tuple), 
as above.
Best wishes
Rob Cliffe

On 02/03/2022 00:12, Larry Martell wrote:
> If I have 2 lists, e.g.:
>
> os = ["Linux","Windows"]
> region = ["us-east-1", "us-east-2"]
>
> How can I get a list of tuples with all possible permutations?
>
> So for this example I'd want:
>
> [("Linux", "us-east-1"), ("Linux", "us-east-2"), ("Windows",
> "us-east-1"), "Windows", "us-east-2')]
>
> The lists can be different lengths or can be 0 length. Tried a few
> different things with itertools but have not got just what I need.
>
> TIA!



More information about the Python-list mailing list