About the del command for multiple keys:


#1

Hi,

Can I delete multiple items in a single del command?
e.g. del zoo_animals['Sloth', 'Bengal Tiger'] #deletes multiple keys

I tried and it didn't work. Is it in other forms? Or I just have to do it once per line?

Thank you.


#2

The del command permits single element or slice deletion. This works on LISTS, only.

del my_list[1:4]

The above will remove the second through fifth elements from my_list (assuming it has that many).

del my_list[:1]

removes the first element.

Sample usage

str = "abcdefghijklmnopqrstuvwxyz"
lst = list(str)
print lst
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
sub = lst[:]
del sub[20:]
print sub
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']