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.


numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # printing original list content
numbers[0] = 111
print("\nPrevious list content:", numbers) # printing previous list content
numbers[1] = numbers[4] # copying value of the fifth element to the second
print("Previous list content:", numbers) # printing previous list content
print("\nList's length:", len(numbers)) # printing previous list length
###
del numbers[1] # removing the second element from the list
print("New list's length:", len(numbers)) # printing new list length
print("\nNew list content:", numbers) # printing current list content
###
  • Console 

Comments

Popular Posts