Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"

Remember the Jackson rules of optimization:

  • Rule 1: Don't do it.
  • Rule 2 (for experts only): Don't do it yet.

And the Knuth rule:

  • "Premature optimization is the root of all evil."

The more useful rules are in the General Rules for Optimization.

  1. Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong.

  2. Remember the 80/20 rule.

  3. Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%.

  4. Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure.

Bottom Line

You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.

Answer from S.Lott on Stack Overflow
🌐
Python
wiki.python.org › moin › PythonSpeed › PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
Note that putting an import in a function can speed up the initial loading of the module, especially if the imported module might not be required. This is generally a case of a "lazy" optimization -- avoiding work (importing a module, which can be very expensive) until you are sure it is required. This is only a significant saving in cases where the module wouldn't have been imported at all (from any module) -- if the module is already loaded (as will be the case for ...
🌐
JetBrains
blog.jetbrains.com › pycharm › 2025 › 11 › 10-smart-performance-hacks-for-faster-python-code
10 Smart Performance Hacks For Faster Python Code | The PyCharm Blog
November 17, 2025 - From leveraging the inherent efficiency of Python’s built-in functions and high-performance libraries such as NumPy to employing memory-conscious techniques with __slots__ and generators, these fifteen Python performance strategies provide a comprehensive set of tools for enhancing execution speed. The methods explored include optimizing iterative processes with comprehensions, utilizing sets for rapid membership checks, avoiding unnecessary data copies and exception handling overhead, and applying bitwise operations as arithmetic shortcuts.
Discussions

How to optimize python code?
Profiling. Don't even consider trying to optimise the performance of your code until you've got data on which stuff is slow. Most code isn't critical to performance, even in applications with hard-to-hit performance requirements, and it's a waste of time trying to tune the stuff that doesn't matter. Use a profiler to figure out which of your code is taking the most time, and once you know that, focus on that code. My favourite profiler right now is Py-Spy, but if you've only got the standard library at your disposal, cProfile is a good start. More on reddit.com
🌐 r/Python
157
177
January 28, 2022
performance - Optimizing Python Code - Stack Overflow
This page of the python.org wiki provides lots of information about how to speed up python code, though some of it is a bit out of date. Here's the BDFL himself on the subject of optimising loops. More on stackoverflow.com
🌐 stackoverflow.com
Why Python is slow and how to make it faster
Seeing lots of comments being dismissive of the efforts of improving Python is a bit disheartening. Of course you should strive to write proper code, it's doesn't mean that having a good, fast implementation of the language isn't a large improvement. I'm thankful for people working on this, just getting glue code, scripts or not easily JIT'able code to run faster is very cool! More on reddit.com
🌐 r/Python
186
305
January 8, 2024
[deleted by user]
this question is far too broad. what are you trying to accomplish? we don't know you're skill level or even what kind of application you're making. More on reddit.com
🌐 r/Python
34
21
March 1, 2022
Top answer
1 of 16
47

Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"

Remember the Jackson rules of optimization:

  • Rule 1: Don't do it.
  • Rule 2 (for experts only): Don't do it yet.

And the Knuth rule:

  • "Premature optimization is the root of all evil."

The more useful rules are in the General Rules for Optimization.

  1. Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong.

  2. Remember the 80/20 rule.

  3. Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%.

  4. Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure.

Bottom Line

You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.

2 of 16
30

Rather than just punting to C, I'd suggest:

Make your code count. Do more with fewer executions of lines:

  • Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases.
  • Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some wont. The latter is preferable
  • Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1).
  • Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops.
  • If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance.
  • Need to crunch numbers? You might want to check numpy out.
  • Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the Twisted framework.
  • Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter.

If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path.

🌐
SOFTFORMANCE
softformance.com › home › blog › 25 tips for optimizing python performance
Optimizing Python Code for Performance: Tips & Tricks | SoftFormance
January 10, 2024 - Fortunately, code mapping is here to optimize time utilization and accelerate the execution of such loops. Code maps are native structure elements that simplify intricate code, making it more shareable and comprehensible. The more efficient and consolidated the code, the better your Python code speed up.
🌐
Analytics Vidhya
analyticsvidhya.com › home › optimize python code for high-speed execution
Optimize Python Code for High-Speed Execution - Analytics Vidhya
May 28, 2025 - What are some Python-specific strategies to boost code efficiency? Utilize list/dictionary comprehensions, and generator expressions for concise code. Employ caching, memoization, and just-in-time compilation using Numba or static typing via Cython.
🌐
Stackify
stackify.com › 20-simple-python-performance-tuning-tips
Python Performance Tuning: 20 Simple Tips - Stackify
May 2, 2023 - Sometimes you might find yourself wanting to optimize your code with something like this: ... This idea seems to make sense. There might be a lot of animals, and de-duplicating them feels like it might be faster. ... Even though there may be significantly more animals in the list to check, the interpreter is optimized so much that applying the set function is likely to slow things down. Checking “in” a long list is almost always a faster operation without using the set function. The Python list datatype implements as an array.
🌐
TheServerSide
theserverside.com › tip › Tips-to-improve-Python-performance
9 tips to improve Python performance | TheServerSide
Use these tips to identify and fix problems in your Python code to tweak its performance. Speed up Python and NumPy by avoiding the conversion tax · Data and memory transfers in Python come with a hidden performance tax. Here's how to use NumPy for optimal performance by avoiding jumps across ...
Find elsewhere
🌐
Reddit
reddit.com › r/python › how to optimize python code?
r/Python on Reddit: How to optimize python code?
January 28, 2022 -

Hi Pythonistas,

I'm interested in learning what optimization techniques you know for python code. I know its a general statement, but I'm interested in really pushing execution to the maximum.

I use the following -

  1. I declare __slots__ in custom classes

  2. I use typing blocks for typing imports

  3. I use builtins when possible

  4. I try to reduce function calls

  5. I use set lookups wherever possible

  6. I prefer iteration to recursion

Edit: I am using a profiler, and benchmarks. I'm working on a library - an ASGI Api framework. The code is async. Its not darascience. Its neither compatible with pypy, nor with numba..

What else?

🌐
SciPy Lecture Notes
scipy-lectures.org › advanced › optimizing
2.4. Optimizing code — Scipy lecture notes
Make it work reliably: write automated ... tests will capture the breakage. Optimize the code by profiling simple use-cases to find the bottlenecks and speeding up these bottleneck, finding a better algorithm or implementation....
🌐
GeeksforGeeks
geeksforgeeks.org › tips-to-maximize-your-python-code-performance
10 Tips to Maximize Your Python Code Performance - GeeksforGeeks
April 4, 2025 - Use NumPy and SciPy-NumPy and SciPyare powerful libraries that can help you optimize your code for scientific and mathematical computing. UseCython to speed up critical parts of the code.
🌐
HackerEarth
hackerearth.com › home › blog › 4 performance optimization tips for faster python code
Boosting Python Performance: 4 Optimization Tips for Faster Code
February 23, 2024 - To make your code run faster, the most important thing that you can do is to take two minutes before writing any code and think about the data-structure that you are going to use.
🌐
Medium
medium.com › @quanticascience › performance-optimization-in-python-e8a497cdaf11
Performance Optimization in Python | by QuanticaScience | Medium
February 24, 2024 - Use memoization libraries or custom solutions for more complex scenarios · Caching and memoization can significantly reduce the execution time of Python code, especially in applications with heavy data processing or complex calculations.
🌐
Python
python.org › doc › essays › list2str
Python Patterns - An Optimization Anecdote | Python.org
Rule number one: only optimize when there is a proven speed bottleneck. Only optimize the innermost loop. (This rule is independent of Python, but it doesn't hurt repeating it, since it can save a lot of work.
🌐
DEV Community
dev.to › leapcell › python-performance-tips-you-must-know-24n5
Python Performance Tips You Must Know - DEV Community
January 29, 2025 - In Python programming, optimizing the number of function calls is crucial for improving code efficiency. Excessive function calls not only increase overhead but may also consume additional memory, thus slowing down the running speed of the program.
🌐
GeeksforGeeks
geeksforgeeks.org › python › optimization-tips-python-code
Optimization Tips for Python Code - GeeksforGeeks
August 19, 2025 - Local variables are faster because Python doesn’t need to search the global scope each time. Storing frequently used objects or functions locally improves speed and keeps code cleaner.
🌐
KDnuggets
kdnuggets.com › 2021 › 06 › make-python-code-run-incredibly-fast.html
How to Make Python Code Run Incredibly Fast - KDnuggets
October 28, 2022 - Python’s built-in functions are one of the best ways to speed up your code. You must use built-in python functions whenever needed. These built-in functions are well tested and optimized.
🌐
Python⇒Speed
pythonspeed.com › articles › different-ways-speed
330× faster: Four different ways to speed up your code
July 3, 2025 - Efficiency won’t always give you faster results in Python on its own, as in this case, so you might need to first switch to a compiled language and then look for opportunities to speed things up with Efficiency. For example, if we ported the above to Rust, it would end up pretty similar to frequency_1_rust(). We’d then have to apply the Practice of Efficiency to the Rust code to get to the hugely faster frequency_3_rust() by switching from a HashMap to a Vec or Rust array.
Top answer
1 of 4
108

If your question is about optimising python code generally (which I think it should be ;) then there are all sorts of intesting things you can do, but first:

You probably shouldn't be obsessively optimising python code! If you're using the fastest algorithm for the problem you're trying to solve and python doesn't do it fast enough you should probably be using a different language.

That said, there are several approaches you can take (because sometimes, you really do want to make python code faster):

Profile (do this first!)

There are lots of ways of profiling python code, but there are two that I'll mention: cProfile (or profile) module, and PyCallGraph.

cProfile

This is what you should actually use, though interpreting the results can be a bit daunting. It works by recording when each function is entered or exited, and what the calling function was (and tracking exceptions).

You can run a function in cProfile like this:

import cProfile
cProfile.run('myFunction()', 'myFunction.profile')

Then to view the results:

import pstats
stats = pstats.Stats('myFunction.profile')
stats.strip_dirs().sort_stats('time').print_stats()

This will show you in which functions most of the time is spent.

PyCallGraph

PyCallGraph provides a prettiest and maybe the easiest way of profiling python programs -- and it's a good introduction to understanding where the time in your program is spent, however it adds significant execution overhead

To run pycallgraph:

pycallgraph graphviz ./myprogram.py

Simple! You get a png graph image as output (perhaps after a while...)

Use Libraries

If you're trying to do something in python that a module already exists for (maybe even in the standard library), then use that module instead!

Most of the standard library modules are written in C, and they will execute hundreds of times faster than equivilent python implementations of, say, bisection search.

Make the Interpreter do as Much of Your Work as You Can

The interpreter will do some things for you, like looping. Really? Yes! You can use the map, reduce, and filter keywords to significantly speed up tight loops:

consider:

for x in xrange(0, 100):
    doSomethingWithX(x)

vs:

map(doSomethingWithX, xrange(0,100))

Well obviously this could be faster because the interpreter only has to deal with a single statement, rather than two, but that's a bit vague... in fact, this is faster for two reasons:

  • all flow control (have we finished looping yet...) is done in the interpreter
  • the doSomethingWithX function name is only resolved once

In the for loop, each time around the loop python has to check exactly where the doSomethingWithX function is! even with cacheing this is a bit of an overhead.

Remember that Python is an Interpreted Language

(Note that this section really is about tiny tiny optimisations that you shouldn't let affect your normal, readable coding style!) If you come from a background of a programming in a compiled language, like c or Fortran, then some things about the performance of different python statements might be surprising:

try:ing is cheap, ifing is expensive

If you have code like this:

if somethingcrazy_happened:
     uhOhBetterDoSomething()
else:
     doWhatWeNormallyDo()

And doWhatWeNormallyDo() would throw an exception if something crazy had happened, then it would be faster to arrange your code like this:

try:
    doWhatWeNormallyDo()
except SomethingCrazy:
    uhOhBetterDoSomething()

Why? well the interpreter can dive straight in and start doing what you normally do; in the first case the interpreter has to do a symbol look up each time the if statement is executed, because the name could refer to something different since the last time the statement was executed! (And a name lookup, especially if somethingcrazy_happened is global can be nontrivial).

You mean Who??

Because of cost of name lookups it can also be better to cache global values within functions, and bake-in simple boolean tests into functions like this:

Unoptimised function:

def foo():
    if condition_that_rarely_changes:
         doSomething()
    else:
         doSomethingElse()

Optimised approach, instead of using a variable, exploit the fact that the interpreter is doing a name lookup on the function anyway!

When the condition becomes true:

foo = doSomething # now foo() calls doSomething()

When the condition becomes false:

foo = doSomethingElse # now foo() calls doSomethingElse()

PyPy

PyPy is a python implementation written in python. Surely that means it will run code infinitely slower? Well, no. PyPy actually uses a Just-In-Time compiler (JIT) to run python programs.

If you don't use any external libraries (or the ones you do use are compatible with PyPy), then this is an extremely easy way to (almost certainly) speed up repetitive tasks in your program.

Basically the JIT can generate code that will do what the python interpreter would, but much faster, since it is generated for a single case, rather than having to deal with every possible legal python expression.

Where to look Next

Of course, the first place you should have looked was to improve your algorithms and data structures, and to consider things like caching, or even whether you need to be doing so much in the first place, but anyway:

  • This page of the python.org wiki provides lots of information about how to speed up python code, though some of it is a bit out of date.

  • Here's the BDFL himself on the subject of optimising loops.

There are quite a few things, even from my own limited experience that I've missed out, but this answer was long enough already!

This is all based on my own recent experiences with some python code that just wasn't fast enough, and I'd like to stress again that I don't really think any of what I've suggested is actually a good idea, sometimes though, you have to....

2 of 4
3

First off, profile your code so you know where the problems lie. There are many examples of how to do this, here's one: https://codereview.stackexchange.com/questions/3393/im-trying-to-understand-how-to-make-my-application-more-efficient

You do a lot of indexed access as in:

for pair in range(i-1, j):
    if coordinates[pair][0] >= 0 and coordinates[pair][1] >= 0:

Which could be written more plainly as:

for coord in coordinates[i-1:j]:
    if coord[0] >= 0 and cood[1] >= 0:

List comprehensions are cool and "pythonic", but this code would probably run faster if you didn't create 4 lists:

N = int(raw_input())
coordinates = []
coordinates = [raw_input() for i in xrange(N)]
coordinates = [pair.split(" ") for pair in coordinates]
coordinates = [[int(pair[0]), int(pair[1])] for pair in coordinates]

I would instead roll all those together into one simple loop or if you're really dead set on list comprehensions, encapsulate the multiple transformations into a function which operates on the raw_input().

🌐
Plain English
python.plainenglish.io › how-i-speed-up-my-python-scripts-by-300-31030219a6d5
How I Speed Up My Python Scripts by 300% | by Kiran Maan | Python in Plain English
January 25, 2025 - I still remember the time, when I just wrote a Python script in which I had to process a large dataset. It was a small project but for processing that much data, I had to wait…wait..wait for a long time. The task that could be done in a few minutes is dragged into hours. ... Then, I realized something was wrong. My code was not optimized, so I learned to optimize my code after a lot of attempts. It makes my script speed up by 300%.
🌐
Quora
quora.com › How-can-I-optimize-my-Python-code-for-faster-execution-and-efficiency
How to optimize my Python code for faster execution and efficiency - Quora
Answer: Hi, Greetings To optimize python code we have to: 1. Use inbuilt libraries and packages which are present in pyrhon 2. Use loops in optimize way 3. Use key values 4. Use Proper use of global and local concept 5. Use assignment multiple ...