Remove Elements from List by Index or Indices

Python: Remove Elements from List by Index or Indices

Lists are ordered sequences that can contain a wide range of object types. Lists can also have duplicate members. Lists in Python can be compared to arrays in other programming languages. But there is one significant difference. Arrays can only contain elements of the same data type, whereas Python lists can contain items of various data types.

Python Lists include a number of methods for removing items from the list.

This article will go over various methods for removing a single or multiple elements from a list.

Examples:

Input:

givenlist=["hello", "this", "is", "Btech", "Geeks"] , index=2

Output:

["hello", "this", "Btech", "Geeks"]

Remove values from the List Using Indexes or Indices

There are several ways to remove elements from the list using Indexes or Indices some of them are:

 

>Method#1: Using del keyword

“del list object [index]” can be used to exclude an item from a list based on its index location.

The del keyword, on the other hand, will raise IndexError if the list is empty or the specified index is out of range.

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
    # deleting the index
    del givenlist[index]
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]
# given index which is to be removed
index = 2
# passing list and index to removeIndex function to remove the element
print(removeIndex(givenlist, index))

Output:

['hello', 'this', 'Btech', 'Geeks']

It removed the element at position 2 . But what if we try to delete an element with an out-of-range index?

As an example,

we will delete the element at index 10(which doesn’t in this list) the output is:

del givenlist[index]
IndexError: list assignment index out of range

Because the given index was out of bounds, it raised an IndexError. The index position was greater than the

list’s length. To avoid this index error, we should always check to see if the given index is valid.

Below is the implementation:

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
    # deleting the index
    if(index < len(givenlist)):
        del givenlist[index]
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]
# given index which is to be removed
index = 2
# passing list and index to removeIndex function to remove the element
print(removeIndex(givenlist, index))

Output:

['hello', 'this', 'Btech', 'Geeks']

>Method #2: Using pop() function

The list class in Python has a function pop(index) that removes an item from the list at the given index.

However, if the list is empty or the given index is out of range, the pop() function may throw an IndexError.

As a result, we should exercise caution when using this function to delete an item from a list based on its index position.

We wrote a function that deletes an element from a list based on its index. It uses the pop() function internally,

but first checks to see if the given index is valid. Let us illustrate with an example:

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
  # using pop() function
    if index < len(givenlist):
        givenlist.pop(index)
   # returning the list
    return givenlist


# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]
# given index which is to be removed
index = 2
# passing list and index to removeIndex function to remove the element
print(removeIndex(givenlist, index))

Output:

['hello', 'this', 'Btech', 'Geeks']

The function removeIndex() accepts two arguments,

  • A givenlist from which an element must be removed.
  • An index that represents the place in the given list where an element must be removed.

>Method #3: Using slicing

In each of the previous solutions, we changed the list while it was still in place. Slicing, on the other hand, can be used to create a new list by removing the element at a given index from the original list.

To delete an element at index N, for example, divide the list into three parts.

  1. Elements ranging from 0 to N-1
  2. Element at index position N
  3. Elements starting at index position N+1 and continuing to the end of the list.

Below is the implementation:

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
  # using slicing
    givenlist = givenlist[:index] + givenlist[index+1:]
  # returning the list
    return givenlist


# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]
# given index which is to be removed
index = 2
# passing list and index to removeIndex function to remove the element
print(removeIndex(givenlist, index))

Output:

['hello', 'this', 'Btech', 'Geeks']

>Method #4 : Using indices to remove multiple elements

Assume we have a list of 7 elements and want to remove the elements at indexes 1, 5, and 6. We can’t just name the pop after iterating over the specified index positions (index). The element at a given index will be removed by the pop() function, and the index location of all elements after the deleted elements will change as a result (decrease by 1).

The best approach is to sort the index positions in decreasing order and then call the pop() function on the highest to lowest index positions. To make this process as simple as possible, we’ve built a function.

Based on the specified index positions, it may remove multiple elements from a list.

# Function which removes the element at given index and returns list
def removeIndex(givenlist, indices):
    # sorting indices list in reverse order
    indices = sorted(indices, reverse=True)
    # Traverse the indices list
    for index in indices:
        if index < len(givenlist):
            givenlist.pop(index)

    # returning the list
    return givenlist


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]
# given indices list which are to be removed
indices = [1, 2, 3]
# passing list and indices list to removeIndex function to remove the element
print(removeIndex(givenlist, indices))

Output:

['hello', 'Geeks']

Related Programs: