-2

Is there any way to stack list

lis = [['a','b'],
        ['1', '2', '3'],
        ['r', 's', 't','u']]

i hope return

['a1r','a1s','a1t','a1u','a2r','a2s','a2t','a2u','a3r','a3s','a3t','a3u',
'b1r','b1s','b1t','b1u','b2r','b2s','b2t','b2u','b3r','b3s','b3t','b3u']
rogers228
  • 41
  • 4
  • 4
    [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product) – bereal Jul 05 '21 at 07:57
  • Does this answer your question? [combine list elements](https://stackoverflow.com/questions/3551797/combine-list-elements) – AcK Jul 05 '21 at 08:00
  • [All combinations of a list of lists](https://stackoverflow.com/q/798854/1324033) – Sayse Jul 05 '21 at 08:04
  • @ack That question is about `zip`, and the OP needs a cartesian product. – bereal Jul 05 '21 at 08:05
  • @paxdiablo - I'd argue theres no point in creating an answer when plenty of duplicates already exist – Sayse Jul 05 '21 at 08:05

2 Answers2

3

The following will do what you want:

import itertools

lis = [['a','b'],
       ['1', '2', '3'],
       ['r', 's', 't','u']]

r = ["".join(t) for t in itertools.product(*lis)]

This will set r to:

['a1r', 'a1s', 'a1t', 'a1u', 'a2r', 'a2s', 'a2t', 'a2u', 'a3r', 'a3s', 'a3t', 'a3u', 'b1r', 'b1s', 'b1t', 'b1u', 'b2r', 'b2s', 'b2t', 'b2u', 'b3r', 'b3s', 'b3t', 'b3u']
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • Cant I achieve that using while/for loop? – eisha enan Jul 05 '21 at 09:34
  • @eishaenan If you hard-wire it to having exactly three sub-lists, then you can use a nest of three loops (`for` loops would be more direct than `while` loops). If you want it to handle arbitrarily many sub-lists, then you need to keep some state around (the easiest way would be to use a recursive function). – Tom Karzes Jul 05 '21 at 09:36
0

You could achieve that using itertools

from itertools import product
lis = [['a','b'],
        ['1', '2', '3'],
        ['r', 's', 't','u']]

l = list(product(*lis))
l = [''.join(x) for x in l]

Output:

['a1r', 'a1s', 'a1t', 'a1u', 'a2r', 'a2s', 'a2t', 'a2u', 'a3r', 'a3s', 'a3t', 'a3u', 'b1r', 'b1s', 'b1t', 'b1u', 'b2r', 'b2s', 'b2t', 'b2u', 'b3r', 'b3s', 'b3t', 'b3u'] 
Ram
  • 4,724
  • 2
  • 14
  • 22