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)]
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.
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.
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
product([1,2,3], repeat=2)
using itertools as well?