python 示例
列出pop()方法 (List pop() Method)
pop() method is used to remove an element at the specified index/position from the list, the method is called with this list (list from which we have to remove an element) and index is supplied as an argument.
pop()方法用于从列表中删除指定索引/位置处的元素,此方法与该列表(我们必须从中删除元素的列表)一起调用,并且index作为参数提供。
Syntax:
句法:
list_name.pop(index)
Parameter(s):
参数:
index – It is an optional parameter, it represents the index in the list, we have to remove the element. If we do not provide the value then it's default value will be -1 that will represent the last item.
index –这是一个可选参数,它表示列表中的索引,我们必须删除该元素。 如果我们不提供该值,那么它的默认值将是-1 ,代表最后一项。
Return value:
返回值:
The return type of this method is the type of the element, it returns the removed element.
该方法的返回类型是元素的类型,它返回移除的元素。
Example 1:
范例1:
# Python List pop() Method with Example
# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]
# printing the list
print("cars before pop operations...")
print("cars: ", cars)
# removing element from 2nd index
x = cars.pop(2)
print(x,"is removed")
# removing element from 0th index
x = cars.pop(0)
print(x,"is removed")
# printing the list
print("cars before pop operations...")
print("cars: ", cars)
Output
输出量
cars before pop operations...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
Audi is removed
BMW is removed
cars before pop operations...
cars: ['Porsche', 'Lexus', 'Audi']
Example 2:
范例2:
# Python List pop() Method with Example
# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]
# printing the list
print("x before pop operations...")
print("x: ", x)
res = x.pop(0) # will remove 0th element
print(res,"is removed")
res = x.pop() # will remove last element
print(res,"is removed")
res = x.pop(-1) # will remove last element
print(res,"is removed")
# printing the list
print("x after pop operations...")
print("x: ", x)
Output
输出量
x before pop operations...
x: [10, 20, 30, 40, 50, 60, 70]
10 is removed
70 is removed
60 is removed
x after pop operations...
x: [20, 30, 40, 50]
If the index is out of range, "IndexError" will return.
如果索引超出范围,将返回“ IndexError” 。
Example 3:
范例3:
# Python List pop() Method with Example
# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]
# printing the list
print("x before pop operations...")
print("x: ", x)
res = x.pop(15) # will return an error
print(res," is removed")
# printing the list
print("x after pop operations...")
print("x: ", x)
Output
输出量
x before pop operations...
x: [10, 20, 30, 40, 50, 60, 70]
Traceback (most recent call last):
File "main.py", line 10, in <module>
res = x.pop(15) # will return an error
IndexError: pop index out of range
翻译自: https://www.includehelp.com/python/list-pop-method-with-example.aspx
python 示例