Delete elements from python array with given index of elements as list

dhruv

I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

del_list = [0, 4, 11]

desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]

Here is what I have done

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]

for element in index_list:
    del x[element]

print(x)

I get this error. I can figure out that because of deleting elements the list shortens and the index goes out of range. But i am not sure how to do it

Traceback (most recent call last):
IndexError: list assignment index out of range
Navneet

This question already has an answer here. How to delete elements from a list using a list of indexes?.

BTW this will do for you

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]

value_list = []
for element in index_list:
    value_list.append(x[element])

for element in value_list:
    x.remove(element)

print(x)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Delete duplicate elements from an array

Cannot delete elements from array

Accessing NumPy array elements not in a given index list

Remove multiple elements from a list of index with Python

Delete multiple elements from a list

Deriving a list from a given list with additional elements

Add a range of elements to a list at a given index, replacing the its contents from that index in the list and resizing it (if need it)

Delete multiple elements in a list by index in Python

Advanced slicing: Given a list of index, pick different elements from a numpy array

delete elements from list in python and avoid shifting

Retrieve array elements from a list of index

How can I pop elements in a list from a given array of indexes?

How to delete elements from an array?

How to delete all none elements from a list of lists in Python

Python - adding string elements from a list into an array

How to delete elements from a List synchronously by Index?

Swapping elements based on index given from another list

Delete specific elements from a list in python 3

accessing specific elements of dictionary given a list of index

Delete elements of two list with same index in python

Delete dict elements by index list

Python List of Lists How to delete list elements in adjListCopy by index?

index of N highest elements from a list of numpy array

Delete several elements from an array

Replacing certain elements of an array based on a given index

Delete several elements from array

Get elements from list in python by ¿index?

Delete all subarrays having "True" for all elements from a given array

Python delete all elements from a list that are on an odd index