Home  >  Article  >  Backend Development  >  How to delete elements from a list in python

How to delete elements from a list in python

silencement
silencementOriginal
2019-06-11 14:19:3713389browse

How to delete elements from a list in python

The following are examples of several python methods to delete elements in a list

Method 1

Use remove( "") method deletes the specified element. If there is no such element, an error will be reported.

>>> number=[1,3,2,0]
>>> number.remove(1)#删除指定元素1,这里是int类型因此不需要引号
>>> print(number)
[3, 2, 0]

Method 2

##Use the del[index number] function to delete the element with the specified index number.

>>> number=[1,3,2,0]
>>> del number[3]#删除指定索引数的元素,这里0的索引数是3
>>> print(number)
[1, 3, 2]

Method 3

Use the pop() method to pop up elements. When there is no index number in (), the last element will pop up by default

>>> number=[1,3,2,0]
>>> number.pop(1)#弹出索引数为1的元素
3
>>> print(number)#由此看出pop方法可以改变原列表
[1, 2, 0]

Method 4

Use the clear() method. The clear() method will clear the elements in the list. Be careful when using it


>>> number=[1,3,2,0]
>>> number.clear()
>>> number
[]

The above is the detailed content of How to delete elements from a 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