List assignment and list copy



examples/lists/not_copy.py

fruits = ['apple', 'banana', 'peach', 'kiwi']
salad = fruits
fruits[0] = 'orange'
print(fruits)   # ['orange', 'banana', 'peach', 'kiwi']
print(salad)    # ['orange', 'banana', 'peach', 'kiwi']
  • There is one list in the memory and two pointers to it.
  • If you really want to make a copy the pythonic way is to use the slice syntax.
  • It creates a shallow copy.


examples/lists/real_copy.py

fruits = ['apple', 'banana', 'peach', 'kiwi']
salad = fruits[:]

fruits[0] = 'orange'

print(fruits)   # ['orange', 'banana', 'peach', 'kiwi']
print(salad)    # ['apple', 'banana', 'peach', 'kiwi']