Optimizing Small Python Code

Dieter Maurer dieter at handshake.de
Wed Jun 23 12:24:40 EDT 2021


Kais Ayadi wrote at 2021-6-22 08:03 -0700:
>Hi There!
>this is a small python code executed in 61 steps
>
>for n in range(1, 7):
>    print (n)
>    for x in range(0, n):
>        print("     ", x)
>
>can this code be more optimised?

You should proceed as follows:
implement a task in the most straightforward way possible.
Only if you hit a problem look for optimizations -- to solve the problem.
Small pieces of code rarely need optimizations -- unless they are
called very often.

Optimizations often aim to reduce runtime.
In your code, the runtime is dominated by the output.
Output speed is mostly outside your control.
Do not try to optimize the code above for runtime.

--
Dieter


More information about the Python-list mailing list