how to make pythonic Nested List

Question:

I’d like to make nested list

given_list = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] # each element : range(0, n), num of element : m
new_list = [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], ..., [2, 2, 2]] # total num : n^m

How do I make it?

I tried to overlap the for statement m times, but I don’t think it’s pythonic.

Asked By: hyoeun

||

Answers:

Looks like you are trying to compute the product of the lists in given_list:

> from itertools import product
> list(product(*given_list))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]

If you really need a list of lists, rather than a list of tuples, you’ll have to call list on each element.

[list(t) for t in product(*given_list)]
Answered By: chepner
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.