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. So in this case we would remove [3,4]
to give:
a = [[1,2],[5,6],[7,8]]
My current code is:
if b in [i[0] for i in a]:
pos = [i[0] for i in a].index(b)
del a[pos]
This works but it is slow. What would a better way to do this be?
EDIT: I've not tested performance before so I may be doing this wrong but I get this:
def fun1():
lst = [[x, 2*x] for x in range(1000000)]
lst = [x for x in lst if x[0] != 500]
return lst
def fun2():
lst = [[x, 2*x] for x in range(1000000)]
for i in reversed(range(len(lst))):
if lst[i][0] == 500:
del lst[i]
return lst
cProfile.runctx('fun1()', None, locals())
6 function calls in 0.460 seconds
cProfile.runctx('fun2()', None, locals())
6 function calls in 0.502 seconds