For starters, results += result
is not equivalent to results.append(result)
. It just happens to work because result
is iterable, but will effectively flatten all your object together. Put another way, +=
is a somewhat more restricted equivalent of list.extend
, not list.append
. The latter is much closer to results += [result]
, which is clearly less efficient.
Since you have a fixed number of objects, a list comprehension, as suggested by @chepner's answer is perfectly fine.
For cases that have a variable number of objects being generated, I'd recommend a collections.deque
with a generator expression. This is especially important for long sequences. Appending to a list
is amortized to have long-term O(n)
reallocation behavior, but it's a slow O(n)
, and pretty bad in the short term. deques
are much faster than that, and can be turned into a list with a single allocation as soon as the length is known.
from collections import deque
template = 'https://www.chess.com/games/archive/eono619?gameOwner=other_game&gameTypes%5B0%5D=chess960&gameTypes%5B1%5D=daily&gameType=live&page={}'
results = deque(BeautifulSoup(template.format(i), 'html.parser') for i in range(1, n))
results = list(results)