oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

    Python - 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.

    Remove Specified List Item

    The remove() method removes the specified item from the list.

    Example

    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]
    

    Remove Specified List Item with Index

    The pop() method removes the specified item from the list based on the given index.

    Example

    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)]
    

    Remove Specified List Item Using 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']
    

    Remove Consecutive List Items

    You can delete a series of consecutive items from a list with the slicing operator. Take a look at the following example −

    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)]