Because lists are mutable, you can use the del statement to delete an item or section in place:
L = ['test', 'eggs', 'ham', 'toast'] del L[0] # Delete one item print( L ) del L[1:] # Delete an entire section print( L ) # Same as L[1:] = [] # ww w. ja v a 2 s . co m
Because slice assignment is a deletion plus an insertion, you can delete a section of a list by assigning an empty list to a slice (L[i:j]=[]).
Python deletes the slice named on the left, and then inserts nothing.
Assigning an empty list to an index just stores a reference to the empty list object in the specified slot, rather than deleting an item:
L = ['Already', 'got', 'one'] L[1:] = [] # from w ww. j av a2 s . co m print( L ) L[0] = [] print( L )