Home  >  Article  >  Backend Development  >  What is the difference between pop method and remove method in list in python

What is the difference between pop method and remove method in list in python

王林
王林Original
2020-07-18 11:13:187881browse

The difference between the pop method and the remove method in the list in python is: the remove() method is used to remove the first matching item of a certain value in the list; the pop() method is used to remove the list an element (default is the last element) and returns the value of that element.

What is the difference between pop method and remove method in list in python

The difference is as follows:

(Recommended tutorial: python tutorial)

remove() function Used to remove the first occurrence of a value in a list.

remove() method syntax:

list.remove(obj)

If obj is not in the list, a ValueError error will be raised. Usually, the count method is used to check how many obj there are.

The pop() function is used to remove an element from the list (the last element by default) and return the value of the element.

pop() method syntax:

list.pop(obj=list[-1])

Example:

1. pop() function

>>> a = [3, 2, 1]
>>> a.pop(1)

2

>>> a
[3, 1]

2. remove() function

>>> a = [3, 2, 1, 2]
>>> a.remove(2)
>>> a
[3, 1, 2]

The above is the detailed content of What is the difference between pop method and remove method in list in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn