All permutations from 2 lists
Larry Martell
larry.martell at gmail.com
Wed Mar 2 08:29:50 EST 2022
On Tue, Mar 1, 2022 at 7:32 PM Rob Cliffe <rob.cliffe at btinternet.com> wrote:
>
> I would not use `os` as an identifier, as it is the name of an important
> built-in module.
This is part of a much larger data structure, I created a simplified
example. It is not actually called os.
> 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)))
This does not work if region = []. I wrote in question that either
list could be empty.
> 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