3.1.6.5 Operations on lists | slices, del

Slices: continued

As we've said before, omitting both start and end makes a copy of the whole list:
myList = [10, 8, 6, 4, 2] newList = myList[:] print(newList)
The snippet's output is: [10, 8, 6, 4, 2].

The previously described del instruction is able to delete more than just a list's element at once - it can delete slices too:
myList = [10, 8, 6, 4, 2] del myList[1:3] print(myList)
Note: in this case, the slice doesn't produce any new list!
The snippet's output is: [10, 4, 2].

Deleting all the elements at once is possible too:
myList = [10, 8, 6, 4, 2] del myList[:] print(myList)
The list becomes empty, and the output is: [].

Removing the slice from the code changes its meaning dramatically.
Take a look:
myList = [10, 8, 6, 4, 2] del myList print(myList)
The del instruction will delete the list itself, not its content.
The print() function invocation from the last line of the code will then cause a runtime error.


  • Console 

Comments

Popular Posts