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]]
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)
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]]
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]]
You need to remove an item i
but not the condition A[i]==i
:
for i in range(len(A)):
A[i].remove(i)
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]]