Removing elements from sublists within a list in Python

Question:

I have a list A containing many sublists. I want to remove specific element from each sublist. For example, remove element 0 from A[0], remove element 1 from A[1] and so on. But I am getting an error. I present the expected output.

A=[[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]

for i in range(0,len(A)): 
    A[i].remove(A[i]==i)
print(A)

The error is

in <module>
    A[i].remove(A[i]==i)

ValueError: list.remove(x): x not in list

The expected output is

[[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6]]
Asked By: isaacmodi123

||

Answers:

You need to remove an item i but not the condition A[i]==i:

for i in range(len(A)):
    A[i].remove(i)
Answered By: RomanPerekhrest

Probably better to enumerate your list. Also make sure that the value you’re trying to remove actually exists. Use try/except to handle that scenario

A = [[0, 2, 3, 5], [1, 3, 4, 6], [0, 2, 3, 5], [0, 1, 2, 3, 4, 5, 6]]

for i, e in enumerate(A):
    try:
        e.remove(i)
    except ValueError:
        pass

print(A)

Output:

[[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6]]
Answered By: Pingu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.