Python Combinations of Two List Without Repetition
Need to combine two or more lists into tuples? Use zip()
!
1: Pairing Two Lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
merged = list(zip(names, ages))
print(merged)
Output:
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
2: Handling Unequal Lengths
By default, zip()
stops at the shortest list. Use itertools.zip_longest
to fill missing values:
from itertools import zip_longest
list1 = [1, 2, 3]
list2 = ['a', 'b']
merged = list(zip_longest(list1, list2, fillvalue=None))
print(merged)
Output:
[(1, 'a'), (2, 'b'), (3, None)]
3: All combinations of elements of 2 lists
import itertools
a = ["banana", "melon"]
b = [1, 2, 3]
c = list(itertools.product(a, b))
c
result:
[('banana', 1),
('banana', 2),
('banana', 3),
('melon', 1),
('melon', 2),
('melon', 3)]
4. List comprehension
[(x,y) for x in a for y in b]
result:
[('banana', 1),
('banana', 2),
('banana', 3),
('melon', 1),
('melon', 2),
('melon', 3)]
5. List of Tuples
import itertools
list1=['a','b','c']
list2=[1,2]
[list(zip(x,a)) for x in itertools.permutations(b,len(a))]
result:
[[(1, 'banana'), (2, 'melon')],
[(1, 'banana'), (3, 'melon')],
[(2, 'banana'), (1, 'melon')],
[(2, 'banana'), (3, 'melon')],
[(3, 'banana'), (1, 'melon')],
[(3, 'banana'), (2, 'melon')]]
Permutations or combinations?
Here as an excerpt from the Python docs on itertools
That might help you find what your looking for:
Iterator | Arguments | Results |
---|---|---|
product() |
p, q, … [repeat=1] | cartesian product, equivalent to a nested for-loop |
permutations() |
p[, r] | r-length tuples, all possible orderings, no repeated elements |
combinations() |
p, r | r-length tuples, in sorted order, no repeated elements |
combinations_with_replacement() |
p, r | r-length tuples, in sorted order, with repeated elements |
product('ABCD', repeat=2) |
AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD |
|
permutations('ABCD', 2) |
AB AC AD BA BC BD CA CB CD DA DB DC |
|
combinations('ABCD', 2) |
AB AC AD BC BD CD |
|
combinations_with_replacement('ABCD', 2) |
AA AB AC AD BB BC BD CC CD DD |