4

If I have an indefinite amount of lists and I want to write a method for them to concatenate item-wise, what would be the best way to do this? Meaning, I don't have just 2 lists, like list A and list B and can write something like

X = [x+y for x, y in zip(A, B)]

but I will have various lists generated, which must be sequentially concatenated, so I don't know how to iterate over a n number of lists and concatenate them.

The first list will always have 1 or more elements (its length can be different), and the ones after it will always have only 1 element:

['a','b','c'],['foo'], ['bar']....

The result I need is

['afoobar','bfoobar','cfoobar']
nanachan
  • 1,051
  • 1
  • 15
  • 26

2 Answers2

4
from itertools import product

[''.join(prod) for prod in product(['a','b','c'],['foo'], ['bar'])]

# ['afoobar', 'bfoobar', 'cfoobar']

This will work for any number of lists of any length:

[''.join(prod) for prod in product(['a','b','c'],
                                   ['foo1_', 'foo2_'],
                                   ['bar'], ['end'])]
# ['afoo1_barend',
#  'afoo2_barend',
#  'bfoo1_barend',
#  'bfoo2_barend',
#  'cfoo1_barend',
#  'cfoo2_barend']
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
2

Put your indefinite amount of lists into a single list. Take the itertools.product and str.join the results.

>>> from itertools import product
>>> lists = [['a','b','c'],['foo'], ['bar']]
>>> [''.join(x) for x in product(*lists)]
['afoobar', 'bfoobar', 'cfoobar']

(The asterisk in product(*lists) is unpacking the lists again for the call to product, which handles an arbitrary amount of iterables)

timgeb
  • 76,762
  • 20
  • 123
  • 145