Home > other >  Why is this function overwriting my list?
Why is this function overwriting my list?

Time:03-21

I just started on a project of making different types of sorting algorithms for fun, but I just can't figure out why this function is overwriting a variable.

I have a main file:

import bubble

test = [5, 4, 3, 2, 1]

def main():
    print(test)                     # output: [5, 4, 3, 2, 1]
    print(bubble.oneCycle(test))    # output: [4, 3, 2, 1, 5]
    print(test)                     # output: [4, 3, 2, 1, 5] || and not [5, 4, 3, 2, 1]?

if __name__ == "__main__":
    main()

and I have these functions in my "bubble.py" file:

def compareTwo(a, b):
    if a > b:
        return [b, a]
    elif a < b:
        return [a, b]
    else:
        return False

def oneCycle(arr):
    for i in range(len(arr)-1):
        ans = compareTwo(arr[i], arr[i 1])
        arr[i] = ans[0]
        arr[i 1] = ans[1]

    return arr

def fullCycle(arr):
    return arr

I also have a __init__.py file:

from .bubble import compareTwo
from .bubble import oneCycle
from .bubble import fullCycle

So you can read the comments in the main file, but when I'm calling bubble.oneCycle(test) it overwrites my test list. Why is it doing that?

CodePudding user response:

Alright so I have found the anwser; when changing the list in bubble.py, it's using the "test" list, so thereby changing the list. I've fixed it by calling bubble.oneCycle(test.copy()) instead of bubble.oneCycle(test)

CodePudding user response:

It is because of referencing. When the oneCycle function is called with the array argument , it’s reference is passed.

So, the variable arr in the oneCycle function is pointing to the same memory as the test variable in the main function. All the sorting is happening on the original array itself.

This link here but help you understand better. https://stackoverflow.com/a/33066581/14145421

CodePudding user response:

You could use multiple arguments and unpack test into args of oneCycle.

def oneCycle(*args):
    # use args instead of arr, it should work fine.
    .
    .
    .
print(bubble.oneCycle(*test))
  • Related