Reputation: 3235
Here is the code:
class Foo:
def __init__(self):
self.l = [1, 2, 3]
def get_list(self):
return self.l
f = Foo()
l2 = f.get_list()
print(f.get_list())
l2.remove(2)
print(l2)
print(f.get_list())
Here is the run:
>python /tmp/1.py
[1, 2, 3]
[1, 3]
[1, 3]
So the function get_list() returns reference.
Is there a way to have have it return value?
Upvotes: 1
Views: 54
Reputation: 19
You can return the copy of the list like this
def get_list(self):
# It will return shallow copy of the list.
return self.l.copy()
Or, You can also use deepcopy module for deepcopy like this
from copy import deepcopy
def get_list(self):
return deepcopy(self.l)
For eg.
a = [[1,2,3],[2,3]]
b = a.copy()
# If I append something to a, b will be unchanged.
a.append(1)
# a = [[1,2,3],[2,3], 1]
# b = [[1,2,3],[2,3]]
# If I modify any object inside a, it will also reflect in b. i.e. shallow copy.
a[0].append(5)
# a = [[1,2,3,5],[2,3], 1]
# b = [[1,2,3,5],[2,3]]
In case of deepcopy, b still remain unchanged i.e deepcopy also make copies of inner objects.
Upvotes: 1
Reputation: 174
Seems like a good place to use list copying.
class Foo:
def __init__(self):
self.l = [1, 2, 3]
def get_list(self):
return self.l.copy()
or
class Foo:
def __init__(self):
self.l = [1, 2, 3]
def get_list(self):
return self.l[:]
Upvotes: 1