Home > Software engineering >  "If 'b4' in [['a4', 'b4', c4']]" returns False in Pytho
"If 'b4' in [['a4', 'b4', c4']]" returns False in Pytho

Time:01-21

I have a line that states: if 'b4' in [['a4', 'b4', c4',...]]:. b4 is clearly in the list and still it returns False? How is this possible? if 'b4' in [['a4', 'b4', c4',...]] returns False

CodePudding user response:

Check the square brackets (you're effectively creating a nested list)

The correct code should be if 'b4' in ['b4',...]

CodePudding user response:

This is likely because the list inside the if statement is actually a list of lists, and the string 'b4' is not in the outermost list, but rather in a nested list. To check if 'b4' is in the list of lists, you can use a nested loop to iterate through the outer list and then the inner lists, and check if 'b4' is in any of the inner lists.

lst = [['a4', 'b4', 'c4'], ['d4', 'e4', 'f4']]

for inner_lst in lst:
    if 'b4' in inner_lst:
        print(True)
        break
else:
    print(False)

This will return True.

Also you can use List comprehension for the same

lst = [['a4', 'b4', 'c4'], ['d4', 'e4', 'f4']]

print('b4' in [i for sublist in lst for i in sublist])

This will also return True

CodePudding user response:

The string 'b4' is in a sub-list (you have a list if lists)

Perhaps this will clarify...

print('b4' in [['a4', 'b4', 'c4']][0])

Output:

True
  • Related