Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

List assignment and list copy

  • [:]
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.
fruits = ['apple', 'banana', 'peach', 'kiwi']
salad = fruits[:]

fruits[0] = 'orange'

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