0

I have a list like below, I want to find simple permutation with little bit modification,

For Example

l=['a', 'b']

Output:

[('a', 'a'), ('a', 'b'), ('b', 'b')]

I followed,

Try-1

list(itertools.product(L, repeat=2))

returns,

[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]

Try -2

print list(itertools.permutations(['a', 'b']))

returns,

[('a', 'b'), ('b', 'a')]

Try-3

i can do like below,

temp= [tuple(sorted((i,j))) for i in ['a', 'b'] for j in ['a', 'b']]
print list(set(temp))

But it seems inefficient way to solve this.

1 Answer 1

5

Use combinations_with_replacement:

from itertools import combinations_with_replacement

l=['a', 'b']
for c in combinations_with_replacement(l, 2):
    print(c)

Output

('a', 'a')
('a', 'b')
('b', 'b')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.