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

Change a List

  • :
fruits = ['apple', 'banana', 'peach', 'strawberry']
print(fruits)      # ['apple', 'banana', 'peach', 'strawberry']
fruits[0] = 'orange'
print(fruits)      # ['orange', 'banana', 'peach', 'strawberry']

print(fruits[1:3]) # ['banana', 'peach']
fruits[1:3] = ['grape', 'kiwi']
print(fruits)      #  ['orange', 'grape', 'kiwi', 'strawberry']

print(fruits[1:3]) # ['grape', 'kiwi']
fruits[1:3] = ['mango']
print(fruits)      #  ['orange', 'mango', 'strawberry']

print(fruits[1:2]) # ['mango']
fruits[1:2] = ["banana", "peach"]
print(fruits)      # ['orange', 'banana', 'peach', 'strawberry']

print(fruits[1:1]) # []
fruits[1:1] = ['apple', 'pineapple']
print(fruits)      # ['orange', 'apple', 'pineapple', 'banana', 'peach', 'strawberry']
  • Unlike strings, lists are mutable. You can change the content of a list by assigning values to its elements.
  • You can use the slice notation to change several elements at once.
  • You can even have different number of elements in the slice and in the replacement. This will also change the length of the array.