0

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']
1
  • 2
    You assigned one list to five variables. Commented Apr 25, 2019 at 22:00

2 Answers 2

2

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)]
Sign up to request clarification or add additional context in comments.

Comments

1

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 = []

4 Comments

I understand initializing on separate line will work, but if I initialize on same line, then why won't it create a five separate arrays?
@vegabond because it's similar to doing arr1=[] and then doing arr2=arr1, esentially passing the reference of the actual list from arr1 to arr2, resulting in both of the variables pointing to the same list/memory. That's just how Python is built.
@vegabond You explicitly set all the variables to the same object. Why are you surprised that they're all referring to the same object?
A simple test to check that they all point to the same object is by calling id(arr1) and id(arr2) and you will see that they are identical.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.