remove (): remove as element values

remove (): remove as element values

In addition to del keywords, Python also provides remove () method, which will come to a delete operation based on the value of the element itself.

Note that, remove () method removes only the first specified value and the same element, and must ensure that the element is present, otherwise it will raise a ValueError errors. https://www.furuihua.cn/guangzhou/

Remove () method Example:

  1. nums = [40, 36, 89, 2, 36, 100, 7]
  2. # For the first 36 deleted
  3. nums.remove(36)
  4. print(nums)
  5. # 36 deleted the second time
  6. nums.remove(36)
  7. print(nums)
  8. # 78 deleted
  9. nums.remove(78)
  10. print(nums)

operation result:

[40, 89, 2, 36, 100, 7]
[40, 89, 2, 100, 7]
Traceback (most recent call last):
    File "C:\Users\mozhiyan\Desktop\demo.py", line 9, in <module>
        nums.remove(78)
ValueError: list.remove(x): x not in list

The last time deleted because 78 there is no cause error, so we had better judgment about the advance in the use of remove () remove elements.

Guess you like

Origin www.cnblogs.com/furuihua/p/12582464.html