0

Suppose I have a function which returns a modified version of an input, say a sorting algorithm:

def insertion_sort(listToSort):
    for itemToSort in range(1, len(listToSort)):
        for i in range(itemToSort, 0, -1):
            if listToSort[i] < listToSort[i-1]:
                listToSort[i], listToSort[i-1] = listToSort[i-1], listToSort[i]
            else:
               break

Usually I'd expect that I need to return the new modified version. But in Python, it seems like actual parameters are not a copy of the input, but instead a "link" to the input. This is different from other languages I've worked with (C#, C++), is there a reason this choice was made or was it an arbitrary one?

ettolrach
  • 23
  • 5
  • There's only one list object. You modify that object. Python doesn't make implicit copies of the object. Many OO languages work that way, though I couldn't say about C\* in particular. – deceze Jun 26 '20 at 12:10
  • It is exactly like reference types (classes, for instance) in C#. – molbdnilo Jun 26 '20 at 13:42
  • C# definitely works this way, and so does C++. For example, see the docs for `std::sort`, which has return type `void` meaning it does *not* return a sorted copy. – kaya3 Jun 26 '20 at 13:52
  • @kaya3 C++ passes copies to functions unless explicitly told not to. For instance, `std:sort` does not take reference parameters. – molbdnilo Jun 26 '20 at 14:25
  • @molbdnilo That's misleading. If C++'s `std::sort` took a copy of the sequence as its parameter, then it couldn't possibly do anything useful, since it returns nothing. The argument is a reference to a sequence, and the reference is copied by value, the sequence itself is not copied. Python also copies references by value when function parameters are passed (and in all other assignments). The concept of "passing by reference" of function arguments is distinct from the concept of what a reference is; references are values, and can be copied (to give another reference to the same object). – kaya3 Jun 26 '20 at 14:33
  • @kaya3 `std::sort` has no sequence parameter – it takes two iterators, or two iterators and a callable object, by value. Both "pass by reference" and the "references" of C++ are fundamentally different from "references" in C#/Python. C# enables pass by reference with the `ref` key word, Python doesn't have it at all. – molbdnilo Jun 27 '20 at 03:05

0 Answers0