1

If I were to have a 2d array in python, say

lst = [['a','1', '2'], ['b', 1, 2], ['c', 1, 2], ['b', 3, 4]]

I'd like a way to remove any items from lst where the first item is 'b', so that you return with:

[['a','1', '2'], ['c', 1, 2]]

Any help would be greatly appreciated, preferred if only built in libraries are used. Thanks

2 Answers 2

3

Use a list comprehension

lst = [['a','1', '2'], ['b', 1, 2], ['c', 1, 2], ['b', 3, 4]]
lst = [x for x in lst if x[0] != 'b']
print(lst)

prints

[['a', '1', '2'], ['c', 1, 2]]
Sign up to request clarification or add additional context in comments.

Comments

0

Not using an inbuilt library, but would probably be faster if the array is large,

import numpy as np

lst = np.array(lst)
a = lst[np.where(lst[:,0] != 'b')]
a.to_list()

[['a', '1', '2'], ['c', '1', '2']]

Comments

Your Answer

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