Given your lists of prefixes letters
and suffixes numbers
that have to be combined
letters = ['abc', 'def', 'ghi']
numbers = ['123', '456']
Basic
The first solution that comes to mind (especially if you are new to Python) is using nested loops
result = []
for s in letters:
for n in numbers:
result.append(s+n)
and since - as you said - order is irrelevant, also the following will be a valid solution
result = []
for n in numbers:
for s in letters:
result.append(s+n)
The most important downside of both is that you need to define the result
variable before in a way that looks a bit weak.
Advanced
If you switch to list comprehension you can eliminate that extra line
result = [s+n for n in numbers for s in letters]
Expert
Mathematically spoken, you are creating the Cartesian product of numbers
and letters
. Python provides a function for exact that purpose by itertools.product (which, by the way, also eliminates the double for
s)
from itertools import product
result = [''.join(p) for p in product(letters, numbers)]
this may look like overkill in your very example, but as soon as it comes to more components for building results, it may be a big difference, and all tools presented here but itertools.product
will tend to explode then.
For illustration, I conclude with an example that loops over prefixes, infixes, and postfixes:
print([''.join(p) for p in product('ab', '+-', '12')])
that gives this output:
['a+1', 'a+2', 'a-1', 'a-2', 'b+1', 'b+2', 'b-1', 'b-2']