1

I can do this with itertools :

list(permutations([1,2,3],2))
: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

but how do I also generate :

 (1,1),(2,2),(3,3)

of course w/o doing it separately : [(i,i) for i in range(4)]

3
  • 3
    What about product([1,2,3], repeat=2) using itertools as well?
    – Nakor
    Commented Oct 3, 2019 at 19:06
  • ooo.. i see ..i tried product([1,2,3], 2) ;)
    – sten
    Commented Oct 3, 2019 at 19:52
  • TypeError: 'int' object is not iterable
    – sten
    Commented Oct 3, 2019 at 20:00

3 Answers 3

3

Adding to Nakor's comment, it looks like what you want is the cartesian product. You can get that with list(itertools.product([1,2,3],repeat=2)).

Permutations on the other hand, according to the documentation

The code for permutations() can be also expressed as a subsequence of product(), filtered to exclude entries with repeated elements (those from the same position in the input pool)

so it looks like there is no way to use list(itertools.permutations([1,2,3],2)) and get the output that you want without using additional logic.

2
  • @sten: Is this what you wanted?
    – Bill Bell
    Commented Oct 3, 2019 at 19:42
  • this is the one : product([1,2,3], repeat=2)
    – sten
    Commented Oct 3, 2019 at 20:49
1

You are seeking a permutations_with_replacement tool.

That will give n**r results, e.g. 3**2 = 9 total results.

Python does not yet implement this tool; reasons unclear. However, permutations can generally be implemented with a Cartesian product.

Code

Modified from the docs:

def permutations_with_replacement(iter_, r=None):
    """Yield all or some permutations from a replenished pool; from docs."""
    pool = tuple(iter_)
    n = len(pool)
    r = n if r is None else r

    for indices in itertools.product(range(n), repeat=r):
        #if len(set(indices)) == r:
            #print(indices)

        yield tuple(pool[i] for i in indices)

Demo

results = list(permutations_with_replacement([1, 2, 3], r=2))
len(results)
# 9

results
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Equivalently reduced to:

list(itertools.product([1, 2, 3], repeat=2))
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

See also more answers to this question from an earlier post.

0

Nakor got the right answer :

  product([1,2,3], repeat=2)

I made mistake to try :

 list(product([1,2,3],2))

which errors :

  TypeError: 'int' object is not iterable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.