-1

I can't understand while comparing between two codes. output of a is 7 and b is 5, which is correct. But 2nd code, why does another_list show ['egg', 'rice', 'milk', 'bread', 'butter', 'chicken', 'pasta'] in the output? print(another_list) should show ['egg', 'rice', 'milk', 'bread', 'butter', 'chicken'] only, because I have commented out the line another_list = shopping_list.

a = 5
b = a
a += 2
print(a)
print(b)
print()
 
shopping_list = ["egg",
                 "rice",
                 "milk",
                 "bread",
                 "butter",
                 "chicken"]
another_list = shopping_list
shopping_list += ["pasta"]
print(shopping_list)
######another_list = shopping_list
print(another_list)
jdaz
  • 5,964
  • 2
  • 22
  • 34
  • 4
    Does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) – JenilDave Jul 16 '20 at 06:35
  • It is because you are copying the reference. A trick is another_list = shopping_list[:] – sinkmanu Jul 16 '20 at 06:42

1 Answers1

0

You need to copy the elements of the list explicit. Otherwise you just create a second reference for the same data.

another_list = shopping_list.copy()

b0lle
  • 732
  • 6
  • 19