Search code examples
pythonlist

Pythonic way to append list within single loop


I process Word file collecting some info stored inside table. Initialy I had this:

table = [[app.ActiveDocument.Tables(1).Cell(x, y).Range.Text[:-1]
 for y in [3, 4]] for x in range(13, app.ActiveDocument.Tables(1).Rows.Count-2)]

Here I get 2d list to pass further. But sometimes I get a set of tables in a single file. Structure is always the same, so I can use

table += ["here's the same list as above with different index in Tables"]

to append my list with new data and return.

So code is now is:

table = [[]]
for tab in app.ActiveDocument.Tables:
    table += [[tab.Cell(x, y).Range.Text[:-1] for y in [3, 4]] for x in range(13, tab.Rows.Count-2)]
table.remove([])

but PyCharm says that assigning list is not a "nice" way to get things working. Is there a more elegant way to create list and simultaneously append it in a loop? I don't see a way to let Python know that I'm working with list of items and i don't know how to pack this loop inside initial creation of table.


Solution

  • Basically what you are saying with table = [[]]is "I have a list which contains an empty list".

    And with table.remove([]) you are removing that empty list. This doesn't add anything to your program really.

    You can avoid calling table.remove([]) if you do table = [].

    The lists you are appending in the for loop are not affected by this and the problem/warning should also be gone.