How to extract, access and use all values of a list at chosen sublist index?

Viewed 38

My question is the result of the issue I'm fighting with at the moment. What I need to do is to use something like that:

if myString in list[][1]:
   do something

...on a structure like that:

[
[object1Name, string_1, string_2],
[object2Name, string_1, string_2],
[object3Name, string_1, string_2],
[object4Name, string_1, string_2]
]

I need to check if myString is equal to string_1 in any of the top-level list items and (later) also get the index of top-level list items that fulfill the condition.

I am aware that I can implement it using additional for loop with if statement inside to cycle through all elements in top-level list but I wan't to avoid that. I want a one-liner preferably with "in" but if it's not possible anything else.

I also need to do the exact same thing for dictionary instead of list (which I hope will use more or less same solution).

1 Answers

You should use any(..) here:

if any(myString == sublist[1] for sublist in lst):
    # ... do something
    pass

for an iterable of dictionaries, it is exactly the same, except that the key might be a non-integer, like:

if any(myString == subdict[some_key] for subdict in lst):
    # ... do something
    pass

We here thus iterate over the sublists in lst. If for one of the sublists, myString == sublist[1], then this will succeed, otherwise it will fail.

We thus here use a generator. The any(..) will stop from the moment it finds an item that is True. This however still runs in linear time (worst case).

EDIT: We can obtain the first index with:

idx = next((idx for idx, sublist in enumerate(lst) if myString == sublist[1]), None)

this will return None if no such index is present.

or we can retrieve all the indices with list comprehension:

idcs = [idx for idx, sublist in enumerate(lst) if myString == sublist[1]]
Related