Course
Remove List Items
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Remove List Items
The list class methods
remove()
and pop()
both can remove an item from a list. The difference between them is that remove() removes the object given as argument, while pop() removes an item at the given index.Using the remove() Method
The following example shows how you can use the remove() method to remove list items
list1 = ["Rohan", "Physics", 21, 69.75]print ("Original list: ", list1)
list1.remove("Physics")print ("List after removing: ", list1)
It will produce the following output
Original list: ['Rohan', 'Physics', 21, 69.75]List after removing: ['Rohan', 21, 69.75]
Using the pop() Method
The following example shows how you can use the pop() method to remove list items
list2 = [25.50, True, -55, 1+2j]print ("Original list: ", list2)list2.pop(2)print ("List after popping: ", list2)
It will produce the following output
Original list: [25.5, True, -55, (1+2j)]List after popping: [25.5, True, (1+2j)]
Using the "del" Keyword
Python has the "del" keyword that deletes any Python object from the memory.
Example
We can use "del" to delete an item from a list. Take a look at the following example
list1 = ["a", "b", "c", "d"]print ("Original list: ", list1)del list1[2]print ("List after deleting: ", list1)
It will produce the following output
Original list: ['a', 'b', 'c', 'd']List after deleting: ['a', 'b', 'd']
Example
You can delete a series of consecutive items from a list with the slicing operator. Take a look at the following example −
list2 = [25.50, True, -55, 1+2j]print ("List before deleting: ", list2)del list2[0:2]print ("List after deleting: ", list2)
It will produce the following output
List before deleting: [25.5, True, -55, (1+2j)]List after deleting: [-55, (1+2j)]
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.