Noplatts
Noplatts

Reputation: 45

If element is inside a list not working properly in Python

I have two lists like:

readFile = [['String1'], [], ['String2'], []]
stringList = ['String1','String2']

However, after using Python's if statement:

for value in stringList:
  if not value in readStocksFile:
    print(value+" does not exist in this list")

According to Python, the value String1 isn't inside my readFile list which isn't true. What am I doing wrong?

Upvotes: 1

Views: 1094

Answers (4)

Sumit Kumar
Sumit Kumar

Reputation: 21

That does not work because the in readFile there are no string values, instead there are more lists which have string values so one way of correcting it would be:

if not [value] in readFile

because the value is "String1" so the if statement becomes if not ['String1'] in readFile and readFile has the following elements: ["String1"], [], ["String2"] so since ["String1"] is in the readFile list the if statement would not get triggered.

Upvotes: 0

mayur nanda
mayur nanda

Reputation: 1

This is because String1 is of data type string and ['String1'] is of data-type List , Hence String1 is shown not in readFile. For String1 to be in readFile , readFile should be:

readFile = ['String1', '', 'String2', '']

Upvotes: 0

DevScheffer
DevScheffer

Reputation: 499

because is a list inside a list

readFile = [['String1'], [], ['String2'], []]

try this

readFile = ['String1','' , 'String2', '']

Upvotes: 1

flakes
flakes

Reputation: 23624

If you want to keep the check as "Is this string in a list of list of strings", then I would use the any method:

readFile = [['String1'], [], ['String2'], []]
stringList = ['String1','String2']

for value in stringList:
    if not any(value in sublist for sublist in readFile):
        print(value + " does not exist in this list")

The line if not any(value in file for file in readFile) means: if there is not a single case where value is in one of the sublist, then do the print.

Upvotes: 1

Related Questions