Reputation: 251
I have these 5 array initialized to empty value by using multiple assignment. I am trying to add a different value in each of those arrays. However it seems all arrays value are showing same values. How is this possible?
Code
arr1=arr2=arr3=arr4=arr5=[]
def test(arr,fruit):
arr.append(fruit)
test(arr1, "Apple")
test(arr2, "Anar")
test(arr3, "Orange")
test(arr4, "Fig")
print(arr1)
print(arr2)
print(arr3)
print(arr4)
Output
['Apple', 'Anar', 'Orange', 'Fig']
['Apple', 'Anar', 'Orange', 'Fig']
['Apple', 'Anar', 'Orange', 'Fig']
['Apple', 'Anar', 'Orange', 'Fig']
Upvotes: 0
Views: 70
Reputation: 39042
An alternate approach is using list comprehension to do multiple assignment without creating reference to the same list as
arr1, arr2, arr3, arr4, arr5 = [[] for _ in range(5)]
Upvotes: 2
Reputation: 5833
That's because all those variables point to the same array. Instead you want to initialize each one on separate lines:
arr1 = []
arr2 = []
arr3 = []
arr4 = []
Upvotes: 1