Pythonic way to find value in 2D list?

Viewed 2023

With numpy array, you can check a specific column with slicing, i.e. array[:, 0]. For a list, checking whether a 2D element is inside is as simple as ["one", "two"] in some_list. However, just looking if "one" is present requires one to iterate through the elements, i.e. ["one" == item[0] for item in some_list].

I largely prefer numpy array except that my array needs to be modified (adding at the end and removing values). I like to work with list because they are very simple to work with. I am considering dataframe but I feel like I should be able to find some clever and efficient way to this kind of operation using a list.

2 Answers

To check whether item exists at any position in a 2D list list_of_lists, you can do

any(item in sublist for sublist in list_of_lists)

Note, unlike the list-flattening idea of another answer, this solution doesn't require any extra memory to be used.

Not sure if this is what you're asking, but if all you want is to know if an element exists inside a list of lists l, you can flatten l and use the operator in as below:

>> l = [["one", "two"], ["three", "four"]]
>> one_is_in_l = "one" in [item for sublist in l for item in sublist]
>> print(one_is_in_l)
True

You can also use numpy just to do the check with:

>> l = [["one", "two"], ["three", "four"]
>> one_is_in_l = "one" in np.array(l)
>> print(one_is_in_l)
True
Related