Reputation: 37
I would like to find all combinations of my list of numbers without the pair being the same. The code I've written below gives me all combinations. So, I also get [1, 1], [2, 2] and [3, 3], which I'd like to remove.
nr_list = [1, 2, 3]
combinations = []
for a in nr_list:
for b in nr_list:
pair = [a, b]
combinations.append(pair)
print(combinations)
Upvotes: 0
Views: 286
Reputation: 121
from itertools import permutations
nr_list = [1, 2, 3]
print(list(permutations(nr_list, 2)))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
Similar question: link
Upvotes: 2
Reputation: 133
Just don't append the pair to the combinations if the items in pair are equal ie if pair[0] != pair[1]:
Upvotes: 1
Reputation: 327
Try this code
nr_list = [1, 2, 3]
combinations = []
for a in nr_list:
for b in nr_list:
if(a!=b):
pair = [a, b]
combinations.append(pair)
print(combinations)
Upvotes: 0