[SOLVED] Python performance of for loops

Issue

Does first method offer any performance advantage over the second?

Method 1:

for row in soup.select('table.results tbody tr')
    # Do stuff

Method 2:

rows = soup.select('table.results tbody tr')
for row in rows:
    # Do stuff

I often see method 2 in coding examples, but that I don’t see what performance or readability advantage it offers

Notables:

  1. The statement being executed is irrelevant. I am more so wondering if it gets executed multiple times. @trincot has commented that it does NOT. So I suppose this answers my inquiry then

  2. As pointed out, I am also assuming that rows is not reused anywhere else in my code.

Solution

No, the expression is only evaluated once in both cases. You can measure performance yourself and take your conclusions, but any difference you’ll find will be tiny and fluctuating depending on other, external factors.

The assignment to a rows variable happens only in one of the two alternatives, but represents such a tiny overhead that it will be hard to ever measure it.

Readability is a matter of opinion. Choose what you think is most readable.

Answered By – trincot

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *