littlely
littlely

Reputation: 1428

permutate all the values in python list

I have a list a = [1, 1, 1], and I want to permutate the a in different manner, the result maybe like [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 1), (1, 1, 1)]. How can I do it in efficient manner?

Upvotes: 0

Views: 35

Answers (1)

Sam
Sam

Reputation: 1415

I believe your question indicates you have a list of length N(3, in this case, [1, 1, 1]), and you want every possible combination if the element at each position can be 0 or 1. (your question is confusing, as you aren't really permuting [1,1,1]).

What you want is itertools.product, documentation here. It takes a list of iterables, and creates every combination of an item from the first iterable, the second iterable, etc. So in this case we could achieve the goal with:

> import itertools
> zero_and_one = [0, 1]
> combinations = itertools.product(zero_and_one, zero_and_one, zero_and_one)
> print(list(combinations))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

Happy Coding!

Upvotes: 1

Related Questions