Check if element exists in Nth position in list of lists

Viewed 241

Consider having this list:

ini_list = [[1, 2, 5, 10, 7], 
            [4, 3, 4, 3, 21], 
            [45, 65, 8, 8, 9]]

I need to be able to find if 4 exists in any of the 3rd elements of the list of lists. So in this example, I see it does exist on the 2nd list [4, 3, 4, 3, 21], on positions 1 and 3 so it will return true.

I can do this:

elem_to_find = 4
res1 = any(elem_to_find in sublist for sublist in ini_list)

But by doing it this way I'm searching through all the list of list elements not only the 3rd of each list as expected. What would be the right approach?

1 Answers

You can just do this:

res1 = any(elem_to_find == sublist[2] for sublist in ini_list if len(sublist) > 2)

This compares elem_to_find to sublist[2] instead of just sublist, i.e. the 3rd element instead of the whole list. It also makes sure the length of the sublist is greater than 2 (otherwise the 3rd element wouldn't exist).

Below is the entire code with 2 examples:

ini_list = [[1, 2, 5, 10, 7], 
            [4, 3, 4, 3, 21], 
            [45, 65, 8, 8, 9]]

elem_to_find = 4
res1 = any(elem_to_find == sublist[2] for sublist in ini_list if len(sublist) > 2)

print(res1)
# Prints True

ini_list = [[1, 2, 5, 10, 7], 
            [4, 3, 3, 3, 21],  # No longer has 4 in 3rd position
            [45, 65, 8, 8, 9]]

res1 = any(elem_to_find == sublist[2] for sublist in ini_list if len(sublist) > 2)
print(res1)
# Prints False
Related