0

I have a program which is an implementation of a sorting algorithm

def myfunction(data):
    x = [sorted elements...]

Input

mylist = [elements...]
myfunction(mylist)
print(mylist)

The function ends up eventually with a list x, with the same elements which have been sorted, but is a copy of mylist. This means that when the program is run, mylist is returned, instead of x.

How can I alter mylist within myfunction so that is the same as x? Surely there is a way to map x and mylist to each other and then iteratively alter mylist until it matches x?

Okeh
  • 163
  • 1
  • 7
  • Related: [Passing an integer by reference in Python](https://stackoverflow.com/questions/15148496/passing-an-integer-by-reference-in-python) – TrebledJ Mar 30 '19 at 10:51
  • Why would you want to iterative change it? Why not just `return x ` and then write `myList = myfunction(myList)`? – Karl Mar 30 '19 at 10:55

1 Answers1

1
def myfunction(data):
    x = [sorted elements...]
    data[:] = x

This modifies data in-place and sets it to whatever values x contains.

TrebledJ
  • 8,713
  • 7
  • 26
  • 48