Search code examples
pythonloopsarraylistdata-structuresnested-loops

How to do nested loop in python list


operation = ['add','subs']
num_list1 = [[2,4],[7,4],[8,4]]

def calc(op, x,y):
    if op=='add':
        return x+y
    elif op =='subs':
        return x-y

def preview():
    result =[]
    for x,y in num_list1:
        for op in operation:
            result.append([op, calc(op,x,y)])    
    return result


result_preview = pd.DataFrame(preview())
result_preview

And The output I get is:

  1. [add, 6]
  2. [subs, -2]
  3. [add, 11]
  4. [subs, 3]
  5. [add, 12]
  6. [subs, 4]

But I want the output to be like:

  1. [add, 6, 11, 12]
  2. [subs, -2, 3, 4]

Please help me


Solution

  • Why don't you do a one-liner comprehension without even having to define a calc() function:

    output = [[op] + [x + y if op == "add" else x - y for x, y in num_list1] for op in operation]
    

    Then you can print the inner lists:

    for l in output:
       print(l)