Reputation: 377
I have a list l = ['a', 'b', 'c']
and I want to loop through the combination (order doesn't matter) of each paired elements of l
. Doing
import itertools
l= ['a', 'b', 'c']
for pair in itertools.product(l, l):
print(pair)
yields:
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'b')
('b', 'c')
('c', 'a')
('c', 'b')
('c', 'c')
but I want something like:
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'b')
('b', 'c')
('c', 'c')
where the combinations like ('a', 'b')
and ('b', 'a')
doesn't repeat.
what is the best way to do this?
Upvotes: 0
Views: 83
Reputation: 15478
Try this:
arr=['a', 'b', 'c']
for i in range(len(arr)):
for x in arr[i:]:
print((arr[i],x))
Upvotes: 2
Reputation: 11285
import itertools
l = ['a', 'b', 'c']
for pair in itertools.combinations_with_replacement(l, 2):
print(pair)
Upvotes: 3