Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

How to get combination in python?

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.

Upvotes: 0

Views: 62

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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')

Upvotes: 5

Related Questions