0

I have a 2d array, how can I delete certain element(s) from it?

x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
    for j in range(len(x[i])):
        if x[i][j] == 2:
            del x[i][j]

This will destroy the array and returns error "list index out of range".

1
  • So in this case you have a list of lists. Do you want to delete a list, or an element within the list of lists? i.e. do you want to delete [2,3,4,5,2] or just [2] Commented Aug 15, 2019 at 11:47

2 Answers 2

2

you can use pop on the list item. For example -

>>> array = [[1,2,3,4], [6,7,8,9]]
>>> array [1].pop(3)
>>> array 
[[1, 2, 3, 4], [6, 7, 8]]

I think this can solve your problem.

x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
    for j in range(len(x[i])):
        if j<len(x[i]):
            if x[i][j] == 2:
                del x[i][j]

I have tested it locally and working as expected.Hope it will help.

Sign up to request clarification or add additional context in comments.

1 Comment

While this is true, you need to know the indices of the positions you want to delete. Plus these will shift after each list.pop() ending up in a rather complex solution needed.
2

Mutating a list while iterating over it is always a bad idea. Just make a new list and add everything except those items you want to exclude. Such as:

x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
new_array = []
temp = []
delete_val = 2

for list_ in x:
    for element in list_:
        if element != delete_val:
            temp.append(element)
    new_array.append(temp)
    temp = []

x = new_array
print(x)

Edit: made it a little more pythonic by omitting list indices.

I think this is more readable at the cost of temporarily more memory usage (making a new list) compared to the solution that Sai prateek has offered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.