Python Tutorial - List Delete Element (4 Methods)

Python Exercise Lists

Deleting elements in a Python list is divided into the following three scenarios:

  • To delete according to the index of the target element's location, you can use the del keyword or pop method;
  • To delete based on the value of the element itself, you can use the remove method provided by the list (list type);
  • To delete all the elements in the list, you can use the clear method provided by the list (list type).

Delete Elements – Del Method (based on index value) in Python

del is a keyword in Python that is specifically used to perform delete operations. It can delete not only the entire list, but some elements in the list. We have already explained how to delete entire lists in Python Lists, so this section only explains how to delete list elements.

del removes a single element from a list in the format:

del listname [index]

Among them, listname represents the name of the list, and index represents the index value of the element.

del can also delete the middle consecutive element, the format is:

del listname [start: end]

Among them, start indicates the start index and end indicates the end index. del deletes elements from index start to end, excluding elements at end position.

[Example] Use del to delete a single list element:

name = ["Jason", "Alice", "Mark", "Iven", "Peggy"]
#Use positive index
del name [2]
print (name)
#Use negative index
del name [-2]
print (name)
           

The output is:

['Jason', 'Alice', 'Iven', 'Peggy']
['Jason', 'Alice', 'Peggy']

[Example] Use del to delete a continuous section of elements:

name = ["Jason", "Alice", "Mark", "Iven", "Peggy"]
del name [1: 3]
print (name)
name.extend (["Nicole", "Christ"])
del name [-5: -2]
print (name)
           

The output is:

['Jason', 'Iven', 'Peggy']
['Nicole', 'Christ']

Delete Elements – Pop Method (based on index value) in Python

The Python pop method is used to delete the element at the specified index in the list, the specific format is as follows:

listname.pop (index)

Among them, listname represents the name of the list and index represents the index value. If you do not write the index parameter, the last element in the list is deleted by default, similar to the "pop" operation in the data structure.

Example of pop usage:

name = ["Jason", "Alice", "Mark", "Iven", "Peggy"]
name.pop(3)
print(name)
name.pop()
print(name)
           

The output is:

['Jason', 'Alice', 'Mark', 'Peggy']
['Jason', 'Alice', 'Mark']

Most programming languages provide a method corresponding to pop method, which is push method, which is used to add elements to the end of the list, similar to the "push" operation in a data structure. But Python is an exception. Python does not provide a push method, because you can use append method instead of push method.

Delete Elements – Remove Method (based on element value) in Python

In addition to the del keyword, Python also provides a remove () method, which performs a delete operation based on the value of the element itself.

It should be noted that the remove () method will only delete the first element with the same value as the specified value, and must ensure that the element exists, otherwise it will raise a ValueError.

Remove method usage example:

name = ["Jason", "Alice", "Mark", "Iven", "Peggy"]
#First delete Alice
name.remove ("Alice")
print (name)
#Second delete Mark
name.remove ("Mark")
print (name)
#Delete Iven
name.remove ("Nicole")
print (name)
           

The output is:

['Jason', 'Mark', 'Iven', 'Peggy']
['Jason', 'Iven', 'Peggy']
---------------------------------------------------------------------------
ValueError        Traceback (most recent call last)
[ipython-input-75-0c51f3cd30e5] in [module]
7 print (name)
8 #Delete Iven
----> 9 name.remove ("Nicole")
10 print (name)
ValueError: list.remove(x): x not in list

The last deletion, because Nicole does not exist and caused an error, so we better judge in advance when using remove method to delete an element.

Delete Elements – Clear Method (delete all element of the list) in Python

Python clear () is used to delete all elements of the list, that is, to clear the list. Please see the following code:

website= list("www.freelearningpoints.com")
website.clear()
print(website)
           

The output is:

[]

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises