List functions in Python (2)


Buy Me a Coffee

*Memo:

remove() can remove the 1st element matched to value from the list, searching from the left to the right in the list as shown below:

*Memo:

  • The 1st argument is value(Required-Type:Any):
  • 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']
Enter fullscreen mode

Exit fullscreen mode

v = ['A', 'B', ['A', 'B'], ['A', 'B', 'C'], 'A', 'B']

v.remove('C')
v.remove(['A'])
# ValueError: list.remove(x): x not in list
Enter fullscreen mode

Exit fullscreen mode

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(2))
print(v.pop(-3))
# IndexError: pop index out of range
Enter fullscreen mode

Exit fullscreen mode

clear() can remove all elements from the list as shown below:

*Memo:

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)
# []
Enter fullscreen mode

Exit fullscreen mode



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *