[New-bugs-announce] [issue36039] Replace append loops with list comprehensions

Lukas Geiger report at bugs.python.org
Tue Feb 19 11:05:09 EST 2019


New submission from Lukas Geiger <lukas.geiger94 at gmail.com>:

Lib uses loops to append to a new list in quite a few places. I think it would be better to replace those with list comprehensions.

Benefits of this change:
  - List comprehensions are generally more readable than appending to a newly created list
  - List comprehensions are also a lot faster.
    Toy example:
    In [1]: %%timeit
       ...: l = []
       ...: for i in range(5000):
       ...:     l.append(i)
    375 µs ± 1.73 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

    In [2]: %%timeit
       ...: l = [i for i in range(5000)]
    168 µs ± 1.08 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Possible drawbacks:
  - Refactoring can always introduce bugs and makes it harder to get meaningful output from git blame. In this case I think the diff is very manageable, making the changes easy to review.

Personally, I think the codebase would benefit from this change both in terms of some small performance gains and maintainability. I'd be happy to make a PR to fix this.

----------
components: Library (Lib)
messages: 335961
nosy: lgeiger
priority: normal
severity: normal
status: open
title: Replace append loops with list comprehensions
type: performance
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36039>
_______________________________________


More information about the New-bugs-announce mailing list