Deleting Elements
To delete elements from a list, we have several options:
1. The
remove(value) function deletes the
first element in the list that contains the specified
value as an argument.
Therefore, the second element containing the number
2 remains in the list, as only the first one found, at position
1, is removed:
2. We use the
del[index] keyword, which completely deletes an element of the list from memory.
Then, from the new remaining list, we deleted the first element at position
0, which is the value
1:
To completely delete the list from memory, use:
del list.
The pop() Method
The
pop(optional_index) method deletes and returns the last element from the list as a result, or the one sent as an argument through
optional_index:
The function is useful when you want to retrieve and process the value before deleting it. Run the following example:
letters = ["a", "b", "c"]
print(letters.pop())
print(letters.pop())
print(letters.pop())
print(letters)
We printed the last element each time, and at the end...
the list is empty.
Perhaps I want to use them in reverse order, starting from the beginning each time, so I write:
letters = ["a", "b", "c"]
print(letters.pop(0))
print(letters.pop(0))
print(letters.pop(0))
print(letters)
Thus, I retrieved the
first element each time, printed it, and then... it was removed!
Run the program, then proceed to the next page.