*Memo:
- My post explains list functions (1).
- My post explains list functions (3).
- My post explains a list (1).
remove() can remove the 1st element matched to value
from the list, searching from the left to the right as shown below:
*Memo:
- The 1st argument is
value
(Required-Type:Any):- Don't use
value=
.
- Don't use
- Error occurs if
value
doesn't exist.
v = ['A', 'B', ['A', 'B'], ['A', 'B', 'C'], 'A', 'B']
v.remove('B')
print(v)
# ['A', ['A', 'B'], ['A', 'B', 'C'], 'A', 'B']
v.remove('B')
print(v)
# ['A', ['A', 'B'], ['A', 'B', 'C'], 'A']
v.remove(['A', 'B', 'C'])
print(v)
# ['A', ['A', 'B'], 'A']
v[1].remove('A')
# v[-2].remove('A')
print(v)
# ['A', ['B'], 'A']
v[1].remove('B')
# v[-2].remove('B')
print(v)
# ['A', [], 'A']
v.remove([])
print(v)
# ['A', 'A']
v = ['A', 'B', ['A', 'B'], ['A', 'B', 'C'], 'A', 'B']
v.remove('C')
v.remove(['A'])
# ValueError: list.remove(x): x not in list
pop() can remove and throw the element from index
in the list in the range [The 1st index, The last index]
as shown below:
*Memo:
- The 1st argument is
index
(Optional-Default:-1
-Type:int
):-
-1
means the last index. - Don't use
index=
.
-
-
index
can be signed indices(zero and positive and negative indices). - Error occurs if
index
is out of range.
v = ['A', 'B', ['A', 'B'], ['A', 'B', 'C'], 'A', 'B']
print(v.pop()) # B
# print(v.pop(5)) # B
# print(v.pop(-1)) # B
print(v)
# ['A', 'B', ['A', 'B'], ['A', 'B', 'C'], 'A']
print(v.pop(1)) # B
# print(v.pop(-4)) # B
print(v)
# ['A', ['A', 'B'], ['A', 'B', 'C'], 'A']
print(v.pop(2)) # ['A', 'B', 'C']
# print(v.pop(-2)) # ['A', 'B', 'C']
print(v)
# ['A', ['A', 'B'], 'A']
print(v[1].pop(0)) # A
# print(v[-2].pop(-2)) # A
print(v)
# ['A', ['B'], 'A']
print(v[1].pop(0)) # B
# print(v[-2].pop(-1)) # B
print(v)
# ['A', [], 'A']
print(v.pop(1)) # []
# print(v.pop(-2)) # []
print(v)
# ['A', 'A']
print(v.pop(-3))
print(v.pop(2))
# IndexError: pop index out of range
clear() can remove all elements from the list as shown below:
*Memo:
- It has no arguments.
-
del ...[:] can do
clear()
.
v = ['A', 'B', 'C', 'D', 'E', ['F', 'G', 'H'], ['I', 'J']]
v[5].clear()
v[-2].clear()
del v[5][:], v[-2][:]
print(v)
# ['A', 'B', 'C', 'D', 'E', [], ['I', 'J']]
v[6].clear()
v[-1].clear()
del v[6][:], v[-1][:]
print(v)
# ['A', 'B', 'C', 'D', 'E', [], []]
v.clear()
del v[:]
print(v)
# []
Top comments (0)