Adding and removing elements from a List
Updated on 28 Dec 2022
A list doesn’t have to be final. We can add and remove elements if we want. The main list methods we’ll use are
- append
- del
- insert
append
append
will append an element to a list.
students = ['brent', 'paul', 'andrea']
students.append('late person')
print(students)
del
del
will delete an element from the list at the given index or index range.
Info: Remember a list index starts at 0
In the example below, we should be deleting ‘paul’ which is at index 1.
students = ['brent', 'paul', 'andrea']
del students[1]
print(students)
You can check the documentation for other operations that can be performed.
insert
Similar to del
, insert
will insert an element at a given index location. This can be useful if we want to add an element inbetween other existing values.
students = ['brent', 'paul', 'andrea']
students.insert(1, 'inserted person')
print(students)