Python3 function not returning complete list

Question:

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)
Asked By: RD Department

||

Answers:

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)
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.