[Python] Remove elements from a list
.
(1) Using the del keyword
(2) Using the list.remove(x) method
(3) Using the list.pop([x]) method
... ... ...
(1) Using the del keyword:
# Sample Code 1
list1 = [0, 1, 2, 3, 4, 5, 6]
del list1[0]
print(list1)
# [1, 2, 3, 4, 5, 6]
del list1[-1]
print(list1)
# [1, 2, 3, 4, 5]
del list1[:2]
print(list1)
# [3, 4, 5]
(2) Using the list.remove(x) method:
# Sample Code 2
list1 = [0, 1, 2, 3, 4, 5, 6]
list1.remove(2)
print(list1)
# [0, 1, 3, 4, 5, 6]
(3) Using the list.pop([x]) method:
# Sample Code 3
list1 = [0, 1, 2, 3, 4, 5, 6]
list1.pop()
print(list1)
# [0, 1, 2, 3, 4, 5]
list_removed = list1.pop(4)
print(list1)
# [0, 1, 2, 3, 5]
// End
沒有留言:
張貼留言