How to Modify an Item Within a List in Python
In this tutorial, you will learn how to modify an element of a Python list.
TLDR solution
z = [e0, e1, e3]
# append a an element
z.append(e4)
# delete an element (y)
z.pop(index_y)
# replace a single element
z[index_y] = new_value
# replace all occurences of a value using list comprehension
z = [new_value if x == y else x for x in z]
Add an Element to a List
Suppose, you want to append mackerel to list of fishes:
fish = ['salmon', 'pufferfish', 'shark']
fish.append('mackerel')
print(fish)
The new list:
['salmon', 'pufferfish', 'shark', 'mackerel']
Delete an Element from a List
Let's undo the addition by popping the element out of the list:
# specify the index of the element you want to remove
fish.pop(3)
print(fish)
The output:
['salmon', 'pufferfish', 'shark']
Replace an Element of a List
Suppose, you want to change the first element (salmon) of the fish list to mackerel.
If it's a small list, you can just select the element and assign the new value.
Otherwise, it is more convenient to use a list comprehension:
fish = ['salmon', 'pufferfish', 'shark']
# select element and assign value
fish[0] = 'mackerel'
# or use list comprehension
fish = ['mackerel' if x == 'salmon' else x for x in fish]
print(fish)
Note that indices start at 0. The output:
['mackerel', 'pufferfish', 'shark']
That's it! You just learned how to modify a list in Python.