Skip to content Skip to sidebar Skip to footer

Search For Multiple Sublists Of Same List In Python

I need Python to search all the sublists of a given list, but this does not work when I'm searching for an element contained in only one of them. For example, this is my code: data

Solution 1:

Try using a boolean tag. For example:

data = [[4,5],[4,7]]
search = 5
found = false
for sublist in data:
    if search in sublist:
        print("there", sublist)
        found = true
if found == false:
    print("not there")
    print(data)

This way the print data is outside the for loop and won't be printed each time a sublist is found that does not contain search.


Solution 2:

What you were probably trying to write:

data = [[4,5],[4,7]]
search = 4
found = False
for sublist in data:
    if search in sublist:
        found = True
        break
# do something based on found

A better way to write that:

any(search in sublist for sublist in data)

Solution 3:

data = [[4,5],[4,7]]
search = 4
found_flag = False
for sublist in data:
    if search in sublist:
        print("there", sublist)
        found_flag = True

#     else:
#        print("not there")
#        print(data)
if not found_flag:
    print('not found')

There is no reason to include the else clause if you don't want to do anything with the sub-lists that don't include the search value.

A nifty use of else is after the for block (but this only will find one entry) (doc):

data = [[4,5],[4,7]]
search = 4
for sublist in data:
    if search in sublist:
        print("there", sublist)
        break
else:
    print 'not there'

which will execute the else block if it makes it through the whole loop with out hitting a break.


Solution 4:

You might be looking for

for sublist in data:
    if search in sublist:
        print("there", sublist)
        break
    else:
        print("not there")

print(data)

Solution 5:

data = [[4,5],[4,7],[5,6],[4,5]]

search = 5

for sublist in data:

if search in sublist:

    print "there in ",sublist

else:
    print "not there in " , sublist

there in [4, 5]

not there in [4, 7]

there in [5, 6]

there in [4, 5]

I just tried your code, and i am not seeing anything wrong while searching 5


Post a Comment for "Search For Multiple Sublists Of Same List In Python"