How to delete elements from a list in python

silencement
Release: 2019-06-22 13:44:18
Original
8333 people have browsed it

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]
Copy after login

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]
Copy after login

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]
Copy after login

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
[]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!