0

I have two lists, a list of numbers list_n and a list of powers list_p. Then I combine these two lists in a list of tuples, list_t.

list_n = [2, 3, 5, 7]
list_p = [0, 1, 2, 3]
list_t = [[(n, p) for p in list_p] for n in list_n]

list_t is now:

list_t = [
    [(2, 0), (2, 1), (2, 2), (2, 3)],
    [(3, 0), (3, 1), (3, 2), (3, 3)],
    [(5, 0), (5, 1), (5, 2), (5, 3)],
    [(7, 0), (7, 1), (7, 2), (7, 3)]
]

So far so good...

In the next step, I try to create a combination list list_c, that looks like:

list_c = [
    [(2, 0), (3, 0), (5, 0), (7, 0)],
    [(2, 1), (3, 0), (5, 0), (7, 0)],
    [(2, 2), (3, 0), (5, 0), (7, 0)],
    [(2, 3), (3, 0), (5, 0), (7, 0)],
    [(2, 0), (3, 1), (5, 0), (7, 0)],
    [(2, 1), (3, 1), (5, 0), (7, 0)],
    [(2, 2), (3, 1), (5, 0), (7, 0)],
    [(2, 3), (3, 1), (5, 0), (7, 0)],
    [(2, 0), (3, 2), (5, 0), (7, 0)],
    [(2, 1), (3, 2), (5, 0), (7, 0)],
    [(2, 2), (3, 2), (5, 0), (7, 0)],
    [(2, 3), (3, 2), (5, 0), (7, 0)],
    ...
    ...
]

But cannot get the expected list if I had tried the line below:

list_c = list(itertools.product(t for t in list_t))

# list c is now
# list_c = [
#     ([(2, 0), (2, 1), (2, 2), (2, 3)],)
#     ([(3, 0), (3, 1), (3, 2), (3, 3)],)
#     ([(5, 0), (5, 1), (5, 2), (5, 3)],)
#     ([(7, 0), (7, 1), (7, 2), (7, 3)],)
# ]

Btw, I can get the expected list if I had tried with 4 distinct lists:

list_2 = [(2, 0), (2, 1), (2, 2), (2, 3)]
list_3 = [(3, 0), (3, 1), (3, 2), (3, 3)]
list_5 = [(5, 0), (5, 1), (5, 2), (5, 3)]
list_7 = [(7, 0), (7, 1), (7, 2), (7, 3)]
list_c = list(itertools.product(list_2, list_3, list_5, list_7))

After the last line, list_c is now:

list_c = [
    ((2, 0), (3, 0), (5, 0), (7, 0)), 
    ((2, 0), (3, 0), (5, 0), (7, 1)), 
    ((2, 0), (3, 0), (5, 0), (7, 2)), 
    ((2, 0), (3, 0), (5, 0), (7, 3)), 
    ((2, 0), (3, 0), (5, 1), (7, 0)), 
    ((2, 0), (3, 0), (5, 1), (7, 1)), 
    ((2, 0), (3, 0), (5, 1), (7, 2)), 
    ((2, 0), (3, 0), (5, 1), (7, 3)), 
    ((2, 0), (3, 0), (5, 2), (7, 0)), 
    ((2, 0), (3, 0), (5, 2), (7, 1)),
    ...
    ...
]

Can somebody explain how to arrange the line below to get the expected result?

list_c = list(itertools.product(t for t in list_t))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
ssd
  • 2,340
  • 5
  • 19
  • 37
  • 1
    To answer your question directly, that's just not how you do it. The question I linked explains how to do it. And just in case it's not obvious, the generator expression is totally unnecessary here. – wjandrea Jun 18 '23 at 18:45
  • ty @wjandrea, was so simple & worked like charm. After your comment, I remembered that I used trick several times when expanding an existing class & informing the superclass to be aware and `__init__` using `**kwargs`. – ssd Jun 19 '23 at 11:38

0 Answers0