I had a similar problem and found a solution here . It works without having to import any module.
Suppose the list:
people = ["Lisa","Pam","Phil","John"]
A simplified single-line solution will look like this.
All possible pairs , including duplicates:
result = [foo(p1, p2) for p1 in people for p2 in people]
All possible pairs, excluding duplicates :
result = [foo(p1, p2) for p1 in people for p2 in people if p1 != p2]
Unique pairs where order doesn't matter:
result = [foo(people[p1], people[p2]) for p1 in range(len(people)) for p2 in range(p1+1,len(people))]
If you do not want to work, but just to get pairs, removing the foo function and using only a tuple will be enough.
All possible pairs , including duplicates:
list_of_pairs = [(p1, p2) for p1 in people for p2 in people]
Result:
('Lisa', 'Lisa') ('Lisa', 'Pam') ('Lisa', 'Phil') ('Lisa', 'John') ('Pam', 'Lisa') ('Pam', 'Pam') ('Pam', 'Phil') ('Pam', 'John') ('Phil', 'Lisa') ('Phil', 'Pam') ('Phil', 'Phil') ('Phil', 'John') ('John', 'Lisa') ('John', 'Pam') ('John', 'Phil') ('John', 'John')
All possible pairs, excluding duplicates :
list_of_pairs = [(p1, p2) for p1 in people for p2 in people if p1 != p2]
Result:
('Lisa', 'Pam') ('Lisa', 'Phil') ('Lisa', 'John') ('Pam', 'Lisa') ('Pam', 'Phil') ('Pam', 'John') ('Phil', 'Lisa') ('Phil', 'Pam') ('Phil', 'John') ('John', 'Lisa') ('John', 'Pam') ('John', 'Phil')
Unique pairs where order doesn't matter:
list_of_pairs = [(people[p1], people[p2]) for p1 in range(len(people)) for p2 in range(p1+1,len(people))]
Result:
('Lisa', 'Pam') ('Lisa', 'Phil') ('Lisa', 'John') ('Pam', 'Phil') ('Pam', 'John') ('Phil', 'John')
Edit: after the redistribution, to simplify this decision, I realized that this is the same approach as Adam Rosenfield. Hopefully a larger explanation will help some understand this better.