0

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Jobbet
  • 41
  • 3

3 Answers3

3

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)

Jobbet
  • 41
  • 3
  • note though that `copy` only makes a shallow copy, so all the objects in that list are still the same objects, if you only have immutable types there, then fine but any mutable object will get changed in both lists – Matiiss Mar 20 '22 at 19:51
  • 1
    Just to shed some light on this behavior. The reason is; when you assign a list to a variable, then whenever you make any change to that variable (that's mapping to your list) it will actually change the referenced list. You either fix it with a shallow copy or deep copy depending on your need. In your case, since your list is one level deep, your solution (shallow copy) will work. However, if for any reason you make your original list includes child lists, then you need to use deep copy instead. – Ibrahim Al Mahfooz Mar 20 '22 at 19:57
0

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

Jos Raj
  • 31
  • 4
0

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