1

for some reason the variable "a" in the main function changes after the function call. In spite of the fact that "a" doesn't even change within the function. Although even if it did, such changes should not affect its value outside the function, right?

I am using Python 3.6, and I'm out of ideas as to why this is happening. Any help would be greatly appreciated

def mhmArgSort(myNumListInput):
    myNumList=myNumListInput
    cnt=0
    endCnt=len(myNumList)
    NumListSortedIndices=[]
    for cnt1 in range(len(myNumList)):
        smallestNum=100000000000
        smallestNumIndex=0
        for cnt in range(len(myNumList)):
            if myNumList[cnt]<smallestNum:
                smallestNum=myNumList[cnt]
                smallestNumIndex=cnt
        NumListSortedIndices.append(smallestNumIndex)
        myNumList[smallestNumIndex]=100000000000
    return NumListSortedIndices

a=[1,2,3,4,-1,0,3]
print(a)
b=mhmArgSort(a)
print(a)
print(b)


This produces the following result:
[1, 2, 3, 4, -1, 0, 3]
[100000000000, 100000000000, 100000000000, 100000000000, 100000000000, 100000000000, 100000000000]
[4, 5, 0, 1, 2, 6, 3]
Moe
  • 11
  • 1
  • 1
    The variable `a` doesn't change—it's still just a name for the same list—but the value of that list does, because you're calling `append` on it. If you don't want that, you can copy the list (e.g., slice it with `[:]`) and mutate the copy, or you can use non-mutating operations like `lst = lst + [x]`, or you can explicitly build up a whole new list and return that. Usually the last one is most pythonic (especially if you can rewrite things in terms of a function or two and a comprehension that applies them), but they all work. – abarnert Mar 23 '18 at 17:34
  • You can see, what @abarnert describes, when you run your script on [PythonTutor](http://pythontutor.com/visualize.html#mode=edit) – Mr. T Mar 23 '18 at 17:36
  • Thanks so much, this explains one part of the question. Nevertheless, isn't myNumListInput a local variable? So shouldn't any such changes remain within the scope of the function? – Moe Mar 23 '18 at 18:03

0 Answers0