-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New simplify rule: use sum
over len
+ if
#13050
Comments
Your example suggests using the sum of a generator over the length of a list comprehension. Not sure if this was deliberate, but if this rule were to be accepted, it should probably persist iterable type given the discourse (#10838). |
That was deliberate. I would always prefer generator for brevity. |
Randomly join the conversation wonderful work Janosh, but we should also be aware of the slight performance penalty for the With script: import timeit
def condition(val):
return True if val % 2 else False
for seq_len in (10, 100, 1000, 10000, 100000):
sequence = list(range(seq_len))
execution_time_a = timeit.timeit(
'len([val for val in sequence if condition(val)])',
globals=globals(), number=1000
)
execution_time_b = timeit.timeit(
'sum(condition(val) for val in sequence)',
globals=globals(), number=1000
)
print(f"Run time of length {seq_len}:")
print(f"With len if: {execution_time_a:.4f}")
print(f"With sum: {execution_time_b:.4f}")
print(f"Ratio: {execution_time_a / execution_time_b:.4f}\n") I got (Python 3.12.5, MacOS 14.6.1, M3 chip):
|
Running the same script on Python 3.12 with a sum of a list comprehension (
On 3.9,
|
Thanks a lot for the input @tjkuson. Interestingly my previous results were also generated with Python 3.12 on MacOS 14.6.1 with M3 chip (sorry I forgot to mention these details, would update the results). |
example
The text was updated successfully, but these errors were encountered: