Search code examples
pythonlisttuplesenumerate

Check whether a list is present in sublist containing list, tuples


I have a list containing sublists and the sublists contain other lists and tuples something like this

[[(1.0, 1.5), [2, 2], (1.5, 1.0)], [(1.1428571343421936, 0.28571426868438721), [1, 0], (0.5, 0.0)], [(0.66666668653488159, 0.0), [0, 0], [0, 1], (0.5, 1.25)]]

I want to search whether [2,2] exists in a sublist or not and print the index of that sublist containing [2,2]. For eg. the sublist containing [2,2] is 0.

I tried using the following code but it gives all the elements in an increasing fashion.

for index, value in enumerate(flat_list):
    if value == [xpred,ypred]:
        print(index)

Please suggest some alternative !!


Solution

  • Try this

    l = [[(1.0, 1.5), [2, 2], (1.5, 1.0)], [(1.1428571343421936, 0.28571426868438721), [1, 0], (0.5, 0.0)], [(0.66666668653488159, 0.0), [0, 0], [0, 1], (0.5, 1.25)]] 
    
    is_in_l = [l.index(pos) for pos in l if [2,2] in pos]
    if is_in_l:
        print('List Available at {} position'.format(is_in_l[0]))
    else:
        print('List not present')