How to reduce these code? for every length I'm using a if statement?

Question:

My code

cummulative_num = [['1', '4', '5', '7'], ['2', '5', '6', '9']]

if len(cumulative_num)==1:
    print(*cumulative_num[0])
out=""
if len(cumulative_num)==2:
    for i in cumulative_num[0]:
        for j in cumulative_num[1]:
            out+= i+j+ " "
print(out)
out=""
if len(cumulative_num)==3:
    for i in cumulative_num[0]:
        for j in cumulative_num[1]:
            for k in cumulative_num[2]:
                out+= i+j+k+ " "
print(out)

output : 12 15 16 19 42 45 46 49 52 55 56 59 72 75 76 79

The output order should be
each first array element is added to every element in the second array

Please provide me a better approach when the array in cumulative_num increases.

Asked By: Santhosh Veluru

||

Answers:

Something like this could work:

The * unpacks the lists into product, no matter how many sublists you may have.

from itertools import product
cummulative_num = [['1', '4', '5', '7'], ['2', '5', '6', '9']]
' '.join([''.join(x) for x in product(*cummulative_num)])

Output

'12 15 16 19 42 45 46 49 52 55 56 59 72 75 76 79'
Answered By: Chris

This code is nothing fancy, but it works well and can be adapted well depending on if you want the data stored.

output = [] #Optional
for i in cummulative_num[0]:
    for j in cummulative_num[1]:
        output.append(f'{i}{j}') #Optional
        print(f'{i}{j}')
Answered By: Omnishroom
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.