0

I'm trying to make a function that takes an input list parameter and do some math inside, returning a new list with the data collected from the math, but I'm always getting an empty list as a result. How do I need to pass the list to the function in order to get this to work?

inputArray = [12,6,7,3,8]

def derive (self, *inputArray):

    outputarray = []

    for i in inputArray:
        operatorA = inputArray[i]
        operatorB = inputArray[i+1]
        if operatorA > operatorB:
            operation = operatorA - operatorB
            outputarray.append(operation)
        else:
            operation = operatorB - operatorA
            outputarray.append(operation)
    print(outputarray)

 derive(inputArray)
RD Department
  • 51
  • 1
  • 1
  • 6

1 Answers1

1

You were misusing for. To iterate through index, you should use for i in range(len(inputArray) - 1). This will iterate through the list of indexes.

Also, you created a function that requires 2 arguments, but call it with just one, so I removed self.

And to finish, I believe you used the * in an attempt to refer to the string address. That's C/C++ syntax, but won't work on python. Instead, you can return the value to the original string:

inputArray = [12,6,7,3,8]

def derive (inputArray):

    outputarray = []

    for i in range(len(inputArray)-1):
        operatorA = inputArray[i]
        operatorB = inputArray[i+1]
        if operatorA > operatorB:
            operation = operatorA - operatorB

        else:
            operation = operatorB - operatorA

        outputarray.append(operation)
    print(outputarray)
    return(outputarray)

inputArray = derive(inputArray)
Pedro Martins de Souza
  • 1,406
  • 1
  • 13
  • 35
  • 1
    BTW, the whole function (without the printing) could be rewritten as: `def derive(values):` `return [abs(values[i] - values[i+1]) for i in range(len(values)-1)]`. – Matthias Dec 21 '18 at 13:59
  • 1
    Alternative for the function body: `return [abs(i - j) for i, j in zip(values, values[1:])]` – Matthias Dec 21 '18 at 14:02