2
votes

I have a list say x=[1,2,3,4,5] and want to look at different permutations of this list taken two number at a time.

x=[1,2,3,4,5] 
from itertools import permutations
y=list(i for i in permutations(x,2) if i[0]<i[1])
print(y)

output: [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

But i also want [(1,1),(2,2),(3,3),(4,4),(5,5)] in the output.How to rectify this?

1
I hope you can add them yourself, can't you? - Miraj50
Don't use list(<genexpr>). Just use a list comprehension (replace the list(...) with [...]). - Martijn Pieters
@Miraj50 This is just a part of the question.There can be any number of values in the list - Demonking28
Yes, so after that do y.extend([(i,i) for i in x]). - Miraj50
So you want to have combinations with repeats? Is it that you want unique sets of the product of x, really? - Martijn Pieters

1 Answers

4
votes

You want combinations_with_replacement() instead:

>>> from itertools import combinations_with_replacement
>>> list(combinations_with_replacement(x, 2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5)]