Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Remove elements at Indices in List

Python – Remove elements at Indices in List

Given List, remove all the elements present in the indices list in Python.

Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5] 
Output : [5, 6, 7, 2, 10] 
Explanation : 3, 6, and 1 has been removed.

Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2] 
Output : [5, 6, 7, 8, 1, 2, 10] 
Explanation : 3 has been removed.  

In this article, we will cover how to Remove items at a specific index from Python List, and cover different methods that are listed below:

  • Remove an item by index and get its value using pop()
  • Remove items by index or slice using del.
  • Remove items at a specific index using enumerate() + loop 
  • Remove items at a specific index using enumerate() + list comprehension

Method 1: Remove an item by index and get its value using pop()

In this example, we will use the pop method to remove the element from the list, here in the pop we will pass the index value to remove the element at that position.

Python3




# initializing list
test_list = [5, 6, 3, 7, 8, 1, 2, 10]
 
test_list.pop(1)
print(test_list)


Output:

[5, 3, 7, 8, 1, 2, 10]

Time complexity: O(n), where n is the length of the list. 
Auxiliary space: O(1), since the operation does not require any additional space besides the list itself.

Method 2: Remove items by index or slice using del

In this example, we will use the del keyword to delete the specific elements present in the list. Here we will remove multiple items from the list by index. Please note that we need to sort the indices in reversed order to ensure that the shift of indices induced by the deletion of elements at lower indices won’t invalidate the index specifications of elements at larger indices.

Python3




test_list = [5, 6, 3, 7, 8, 1, 2, 10, 5]
indices=[3,7]
 
for i in sorted(indices, reverse=True):
    del test_list[i]
     
print(test_list)


Output:

[5, 6, 3, 8, 1, 2, 5]

Time complexity: O(nlogn), where n is the length of the test_list. 
Auxiliary Space: O(1), constant extra space is required

Method 3: Remove items at a specific index using enumerate() + loop

In this, we iterate for all the elements, and if the index is present in the list, then that index element is omitted from the result list.

Python3




# Python3 code to demonstrate working of
# Remove elements at Indices in List
# Using loop
 
# initializing list
test_list = [5, 6, 3, 7, 8, 1, 2, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing idx list
idx_list = [2, 4, 5, 7]
 
res = []
for idx, ele in enumerate(test_list):
     
    # checking if element not present in index list
    if idx not in idx_list:
        res.append(ele)
 
# printing results
print("Filtered List after removal : " + str(res))


Output:

The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]

Time complexity: O(n), where n is the length of the input list test_list
Auxiliary space: O(n), where n is the length of the input list test_list. 

Method 4: Remove items at a specific index using enumerate() + list comprehension

In this, we perform the task of iteration using list comprehension in a compact way, the rest of the methods are similar to the above.

Python3




# Python3 code to demonstrate working of
# Remove elements at Indices in List
# Using enumerate() + list comprehension
 
# initializing list
test_list = [5, 6, 3, 7, 8, 1, 2, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing idx list
idx_list = [2, 4, 5, 7]
 
# one-liner to test for element in index list
res = [ele for idx, ele in enumerate(test_list) if idx not in idx_list]
 
# printing results
print("Filtered List after removal : " + str(res))


Output:

The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]

Time Complexity: O(n), where n is the length of the original list test_list. 
Auxiliary Space: O(m), where m is the length of the index list idx_list. 

Method#5: Using Recursive method.

Algorithm:

1. If the input index list is empty, return the original list.
2. Extract the first index from the input index list and recursively process the rest of the list.
3. Remove the element at the current index from the result of the recursive call.
4. Return the updated list.

Python3




def remove_elements_at_indices(test_list, idx_list):
    # Base case: if index list is empty, return original list
    if not idx_list:
        return test_list
 
    # Recursive case: extract first index and recursively process the rest of the list
    first_idx = idx_list[0]
    rest_of_indices = idx_list[1:]
    sub_list = remove_elements_at_indices(test_list, rest_of_indices)
 
    # Remove element at current index
    sub_list.pop(first_idx)
 
    return sub_list
test_list = [5, 6, 3, 7, 8, 1, 2, 10]
idx_list = [2, 4, 5, 7]
print("The original list is : " + str(test_list))
 
res = remove_elements_at_indices(test_list, idx_list)
print("Filtered List after removal : " + str(res))


Output

The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]

Time complexity: O(m*n)

The function removes elements from the list for each index in the input index list, so the time complexity is O(m*n), where m is the length of the index list and n is the length of the input list.

Auxiliary Space:  O(max(m, n))

The function uses a recursive approach, so the space complexity is O(m), where m is the length of the input index list due to the recursive call stack. However, the space complexity of the list created is also O(n) as each element is removed one by one. So, the overall space complexity is O(max(m, n)).

 Method #6: Using filter() and lambda function:

Approach:

Create a new list using filter() function and lambda function.
The lambda function takes each element in test_list, and checks if its index is not in idx_list. If the index is not in idx_list, the lambda function returns True and the element is kept in the new list. If the index is in idx_list, the lambda function returns False and the element is filtered out.
The filtered new list is assigned to new_list.
The new_list is printed as the output.

Python3




test_list = [5, 6, 3, 7, 8, 1, 2, 10]
idx_list = [2, 4, 5]
new_list = list(filter(lambda x: test_list.index(x) not in idx_list, test_list))
print(new_list) # Output: [5, 6, 7, 2, 10]


Output

[5, 6, 7, 2, 10]

Time complexity: O(n^2) – We use index() method inside lambda function that has O(n) time complexity.
Auxiliary Space: O(n) – We create a new list to store the remaining elements.

METHOD 7: Using List Comprehension

APPROACH:

1.Create a new list by iterating through the original list and adding elements to the new list only if the index is not in the index list.
2.Return the updated list.

ALGORITHM:

1.Initialize a new list.
2.Iterate through the original list using a for loop.
3.Check if the index of the current element is present in the index list using an if condition.
4.If the index is not present in the index list, add the element to the new list.
5.Return the updated list.

Python3




test_list = [5, 6, 3, 7, 8, 1, 2, 10]
idx_list = [2, 4, 5]
 
new_list = [test_list[i] for i in range(len(test_list)) if i not in idx_list]
 
print("Updated list:", new_list)


Output

Updated list: [5, 6, 7, 2, 10]

Time Complexity: O(n)
Auxiliary Space: O(n)

RELATED ARTICLES

Most Popular

Recent Comments