I created the class Sorter
which sets the variable self.list
in the __init__
equal to a given argument. I then created a function selectionSort
which should copy the value of self.list
into a new variable unsortedList
. That worked out, but when I then change unsortedList
, the self.list
variable changes as well. Here's my code:
class Sorter:
def __init__(self, list):
self.list = list
def selectionSort(self):
unsortedList = self.list
sortedList = []
indexSmallest = 0
while len(unsortedList)>0:
for i in range(len(unsortedList)):
if unsortedList[i] <= unsortedList[indexSmallest]:
indexSmallest = i
sortedList.append(unsortedList[indexSmallest])
unsortedList.pop(indexSmallest)
indexSmallest = 0
return sortedList
sorter = Sorter([2,6,1,8,5])
print(sorter.selectionSort())
I expect self.list
to be the same as before calling the selectionSort()
function but the result I get is an empty self.list
variable.
Use either:
#1
unsortedList = self.list.copy()
Or
#2
unsortedList = self.list[:]
Or
#3
import copy
unsortedList = copy.deepcopy(self.list)
Explanation:
When you do an assignment via =
, it really is referring to the same list just that now that list has 2 different names.
To circumvent this, use #1 or #2 methods -> you would require the .copy()
inbuilt function or using [:]
.
As for #3, this is used when shallow copying isn't enough because you might have mutable objects within the list itself.
For a greater understanding on copy vs deepcopy, visit and read here
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments