Given:
a = [[1,2],[3,4],[5,6],[7,8]]
b = 3
I would like to remove an item of a
that has b
as it\'s first item. S
for i in a[:-1]:
if i[0]==b:
a.remove(i)
What about this?
The output is
[[1, 2], [5, 6], [7, 8]]
You can use a list comprehension:
>>> a = [[1,2],[3,4],[5,6],[7,8]]
>>> b = 3
>>> a = [x for x in a if x[0] != b]
>>> a
[[1, 2], [5, 6], [7, 8]]
If your list are small then you are also try filter ,
a = [[1,2],[3,4],[5,6],[7,8]]
b = 3
print(list(filter(lambda x:x[0]!=b,a)))
output:
[[1, 2], [5, 6], [7, 8]]
Reverse delete a
, modifying it in-place:
for i in reversed(range(len(a))):
if a[i][0] == 3:
del a[i]
An in-place modification means that this is more efficient, since it does not create a new list (as a list comprehension would).
Since OP requests a performant solution, here's a timeit
comparison between the two top voted answers here.
Setup -
a = np.random.choice(4, (100000, 2)).tolist()
print(a[:5])
[[2, 1], [2, 2], [3, 2], [3, 3], [3, 1]]
List comprehension -
%timeit [x for x in a if x[0] != b]
11.1 ms ± 685 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Reverse delete -
%%timeit
for i in reversed(range(len(a))):
if a[i][0] == 3:
del a[i]
10.1 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
They're really close, but reverse delete has a 1UP on performance because it doesn't have to generate a new list in memory, as the list comprehension would.