3.1.4.4 Lists - collections of data | Operations on lists
Removing elements from a list
Any of the list's elements may be removed at any time - this is done with an instruction named
del
(delete). Note: it's an instruction, not a function.
You have to point to the element to be removed - it'll vanish from the list, and the list's length will be reduced by one.
Look at the snippet below. Can you guess what output it will produce? Run the program in the editor and check.
del numbers[1]
print(len(numbers))
print(numbers)
You can't access an element which doesn't exist - you can neither get its value nor assign it a value. Both of these instructions will cause runtime errors now:
print(numbers[4])
numbers[4] = 1
Add the snippet above after the last line of code in the editor, run the program and check what happens.
Note: we've removed one of the list's elements - there are only four elements in the list now. This means that element number four doesn't exist.
Comments
Post a Comment