Search code examples
pythonloopsif-statementnested-loops

Applying conditional after nested loop to the parent loop


I have this code:

values="2"
content=["line1","line2","line3"]
for line in content:
    if values not in line:
        print(line)

which successfully prints out items of content when value 2 is not in those items:

line1
line3

Practically, I am grabbing content out of a file.readlines() method.

Now, I am stuck when I have to compare more than one value against each of the content lines:

values=["2","3"]

Again, I need to check if 2 or 3 are in each of the content lines and print the line when they are not.

I came up with this:

values=["2","3"]
content=["line1","line2","line3"]
for line in content:
    for value in values:
        if value not in line:
            print(line)

But that would normally return this:

line1
line1
line2
line3

I would expect only line1 to be printed out. Any workaround to this?


Solution

  • Use a variable that you set in the nested loop, and check after the loop is done.

    values=["2","3"]
    content=["line1","line2","line3"]
    for line in content:
        in_line = false
        for item in values:
            if item in line:
                in_line = true
                break
        if not in_line:
            print(line)
    

    Or you can use the any function.

    values=["2","3"]
    content=["line1","line2","line3"]
    for line in content:
        if not any(value in line for value in values):
            print(line)