Friday 4 December 2015

Python:list: del: delete elements

By using del statement, you can remove an element from a list using index.


test.py
list=[12, 5, 32, 43, 21, 356, 5, 21]

print(list)

del list[0]
del list[5]

print(list)

$ python3 test.py
[12, 5, 32, 43, 21, 356, 5, 21]
[5, 32, 43, 21, 356, 21]

By using del statement, you can remove slices from list.


test.py
list=[12, 5, 32, 43, 21, 356, 5, 21]
print(list)

del list[2:6]
print(list)


$ python3 test.py
[12, 5, 32, 43, 21, 356, 5, 21]
[12, 5, 5, 21]

By using del statement, you can clear list. ‘del list[:]’ removes all elements from list list.

test.py

list=[12, 5, 32, 43, 21, 356, 5, 21]
print(list)

del list[:]
print(list)


$ python3 test.py
[12, 5, 32, 43, 21, 356, 5, 21]
[]


By using del statement, you can remove variable itself. Once you remove variable, you can’t use it. If you try to use the variable, after it removed, you will get error.

test.py

list=[12, 5, 32, 43, 21, 356, 5, 21]
print(list)

del list
list[0] = 1


$ python3 test.py
[12, 5, 32, 43, 21, 356, 5, 21]
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    list[0] = 1
TypeError: 'type' object does not support item assignment



Previous                                                 Next                                                 Home

No comments:

Post a Comment