Search code examples
pythonpython-3.xpython-docx

How to write multiple for loops in one line of if condition in python? (specific to DOCX)


I have the following code.

for row in table.rows:
    for cell in row.cells:
        if cell.tables:
            <some code>
        else:
            <different code>

But I need it to be written in one line as below so that the <different code> in else will run only once and not multiple times due to the loop.

if any(cell.tables for cell in row.cells for row in table.rows):
    <some code>
else:
    <different code>

However, this one liner is showing Unresolved reference 'row' error at row.cells. This one liner works but have no idea why it doesn't in this docx table case. I'm also open for suggestions if this can be done in a different and better way apart from the one liner if condition.


Solution

  • You have your for clauses reversed. You are trying to reference row in the first for clause and then define it in the second. That's why it doesn't work.

    You mean

    if any(cell.tables for row in table.rows for cell in row.cells):
        ...