Reputation: 281
I've designed a following function that takes a list as a parameter and returns another list.
def function(list):
A = []
B = []
for num in list:
A.append(num)
B.append(A)
return B
In this function, I assumed that the function would append A to A depending on the current state of A. Working under that assumption. I called the function
>>> test([1,2,3,4,5])
expected the output to be
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
However, the result that I get is
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
Why is this? Is there any solution around this problem?
Upvotes: 1
Views: 64
Reputation: 16240
You need to copy it by value. In your current situation, you are passing by reference. Hence, every index gets updated as A
changes. Should be:
B.append(A[:])
Notice the [:]
for copying by value.
To clarify, running your code here we can examine the result of calling function
on [1,2]
:
Now, consider what happens when we make a copy:
def function(list):
A = []
B = []
for num in list:
A.append(num)
B.append(A[:])
return B
print function([1,2])
Also, as a side note: you should change the names of your variables. For example, by declaring the parameter as list
you shadow the list
method.
Upvotes: 3
Reputation: 924
In your code you sending reference instead of data.
Working code
def function(list):
A = []
B = []
for num in list:
A.append(num)
B.append(A[:])
return B
Upvotes: 2
Reputation: 551
Lists are passed by reference. To copy them use the syntax B.append(A[:])
def function(list):
A = []
B = []
for num in list:
A.append(num)
B.append(A[:])
return B
Upvotes: 2
Reputation: 6138
You can append the copy of A
to B
to avoid using the same reference of A
:
for num in list:
A.append(num)
B.append(A[:])
Upvotes: 2