mutable sequences can be modified how?
Replace elements
Delete elements
* often appended (to the end) .append()
* can also specify where in the sequence to .insert
Replacing Single Elements
Replace an element at index 1 by assigning a new element to that index
l = [10, 20, 30]
l[1] = ‘hello’
l –> [10, ‘hello’, 30]
Replacing an entire Slice
Just assign a new collection to the slice
my_list = [1, 2, 3, 4, 5]
my_list [0:3] = ['a', 'b']
my_list [0:3] = ('a', 'b')
my_list [0:3] = 'ab'
my_list --> ['a', 'b', 4, 5]Python uses the elements of the sequence in RHS when assigning to a slice (but not when assigning using a single index)
Deleting Elements
You can delete an element by index
~~~
my_list = [1, 2, 3, 4, 5]
del my_list[1]
my_list à [1, 3, 4, 5]
~~~
Deleting Elements by slice
Can delete an entire slice
my_list = [1, 2, 3, 4, 5] del my_list[1:3] my_list à [1, 4, 5]
Appending Elements
We can append one element
my_list = [1, 2, 3] my_list.append(4) my_list à [1, 2, 3, 4]
To append multiple elements:
We extend the sequence
my_list = [1, 2, 3]
my_list.extend(['a', 'b', 'c'])
my_list.extend(('a', 'b', 'c'))
my_list.extend('abc')
my_list --> [1, 2, 3, 'a', 'b', 'c']Inserting an Element
Instead of appending, we can insert at some index
- use sparingly – this is much slower than appending or extending
my_list = [2, 3, 4, 5] my_list.insert(0, 100) my_list --> [100, 2, 3, 4, 5] my_list = [2, 3, 4, 5] my_list.insert(2, 100) my_list --> [2, 3, 100, 4, 5]
Element is inserted so its position is the index - remaining elements are shifted right