Okeh
Okeh

Reputation: 163

Modifying a list to copy another without making a copy of the original

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?

Upvotes: 0

Views: 36

Answers (1)

TrebledJ
TrebledJ

Reputation: 8987

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

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

Upvotes: 1

Related Questions