Reputation: 749
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?
Upvotes: 2
Views: 416
Reputation: 1124828
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)]
Upvotes: 4