Home > Backend Development > Python Tutorial > How to delete statements in python

How to delete statements in python

little bottle
Release: 2019-06-05 14:54:48
Original
6002 people have browsed it

A friend asked how to implement a delete statement in Python. In fact, there are three methods, namely: del statement, pop() method, and remove() method. The following will give you a detailed introduction.

How to delete statements in python

1. del statement

If you know the position of the element to be deleted in the list, you can use the del statement. Use del to delete a list element at any position, provided its index is known.

For example:

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[1]
print(motorcycles)
Copy after login

After using the del statement to delete a value from the list, you can no longer access it.

2. Pop() method

Method pop() can delete the element at the end of the list and allow you to continue using it. The term pop comes from the analogy that a list is like a stack, and deleting the element at the end of the list is equivalent to popping the element at the top of the stack.

If you want to delete an element from the list and no longer use it in any way, use the del statement; if you want to continue to use it after deleting the element, use the pop method ().

3. remove() method

You don’t know the position of the value you want to delete from the list. If you only know the value of the element you want to remove, use the remove() method.

As an example, suppose we want to remove the value 'ducati' from the list motorcycles.

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
Copy after login

Running result:

['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
Copy after login

Note: The method remove() only deletes the first specified value. If the value to be deleted may appear multiple times in the list, you need to use a loop to determine whether all such values ​​have been deleted.

The above is the detailed content of How to delete statements 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template