It’s been a while and I’m having trouble wrapping my head around a algorithm I’m try to make. Basically, I have two lists and want to get all the combinations of the two lists.
I might not be explaining it correct so here’s a example.
name = 'a', 'b'
number = 1, 2
the output in this case would be:
1. A1 B2
2. B1 A2
The tricky part is I might have more items in the “name” variable than items in the “number” variable(number will always be equal to or less than the name variable).
I’m confused how to do all the combinations (nested for loop?) and even more confused on the logic to shift the items in the name variable in the event that there are more items in name than they are in the number list.
I’m not the best programmer but think I can give it a shot if someone can help me clarify the logic/algoriythm to achieve this. So I have just been stuck on nested for loops.
Update:
Here's the output with 3 variables and 2 numbers:
name = 'a', 'b', 'c'
number = 1, 2
output:
1. A1 B2
2. B1 A2
3. A1 C2
4. C1 A2
5. B1 C2
6. C1 B2
May be simpler than the simplest one above:
without any import
You might want to try a one line list comprehension:
a tiny improvement for the answer from interjay, to make the result as a flatten list.
reference from this link
Without itertools
The simplest way is to use
itertools.product
:I was looking for a list multiplied by itself with only unique combinations, which is provided as this function.
Here as an excerpt from the Python docs on
itertools
That might help you find what your looking for.