Search code examples
pythonreturn-value

Why is there an assertion error when the return value is the same?


So currently, I'm trying to make a simple function that takes in a list of numbers, and creates a new list containing the difference between each element and its subsequent element.

for example

difference([1, 2, 5, 3]) would return [1, 3, -2]

now my code

def difference(numbers):
    for number in numbers:
        i=0
        dif_list=[]
        while i < len(numbers)-1:
            dif_list.append(numbers[i+1]-numbers[i])
            i +=1
        if len(dif_list) == len(numbers)-1:
            return print(dif_list)

This does return the correct output, but when I try to use assertion to check it, it would say there's an assertion error.

assert difference([1, 2, 5, 3]) == [1, 3, -2] gives out

<ipython-input-23-c9c23c8f4955> in <module>
----> 1 assert difference([1, 2, 5, 3]) == [1, 3, -2]

Does anyone now why is this happening?


Solution

  • If you return directly by deleting print, it will work:

    def difference(numbers):
        for number in numbers:
            i=0
            dif_list=[]
            while i < len(numbers)-1:
                dif_list.append(numbers[i+1]-numbers[i])
                i +=1
            if len(dif_list) == len(numbers)-1:
                return (dif_list)
    
    assert difference([1,2,5,3]) == [1, 3, -2]