Search code examples
pythonlistmultiplication

python multiply all elements except ith element in list and return list


Suppose I have a list .I want to multiply its all elements except with the i'th element.

Example:

  • input: [1,2,3,4]
  • output: [24,12,8,6]

Here, the output

 24 is 2*3*4
 12 is 1*3*4
 8 is 1*2*4
 6 is 1*2*3

Any help would be appreciated


Solution

  • A simple solution using two for loops:

    l=[1,2,3,4]
    out=[]
    for i in range(len(l)):
        prod=1 
        for j in range(len(l)):
            if(j!=i): #Iterate through list once more and compare the indices
                prod=prod*l[j]
        out.append(prod) 
    print(out)
    

    Output is: [24, 12, 8, 6]