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. Answer from james_pic on reddit.com
🌐
Python
wiki.python.org › moin › PythonSpeed › PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
The first step to speeding up your program is learning where the bottlenecks lie. It hardly makes sense to optimize code that is never executed or that already runs fast. I use two modules to help locate the hotspots in my code, profile and trace.
🌐
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?

Discussions

performance - Optimizing Python Code - Stack Overflow
I've been working on one of the coding challenges on InterviewStreet.com and I've run into a bit of an efficiency problem. Can anyone suggest where I might change the code to make it faster and more More on stackoverflow.com
🌐 stackoverflow.com
Python code optimization
Hi! I’m writing a Python program to determine if a number n is abundant, that is, if its factors (excluding itself) have a sum greater than n. I know you can just use from sympy import divisors n = int(input()) if sum… More on discuss.python.org
🌐 discuss.python.org
0
0
April 1, 2024
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
Memory Optimization Techniques for Python Developers
From experience, many of these are more likely to be applied as premature optimizations than applied when needed. I would not recommend __slots__ on its own as a memory optimization in the normal course of programming. Far better to use the @dataclass(slots=True), a typing.NamedTuple, or even a more primitive type. Similarly, using array over list is just going to make your code harder to maintain in 98% of cases. Generators and lazy evaluation are good advice in general. They can make code harder to debug, though. Also, creating generators over tiny sets of items in a hot loop will be worse than just allocating the list (generator and iterator overhead). The most frequent memory problem in Python is memory fragmentation, btw. Memory fragmentation occurs when the memory allocator cannot find a contiguous block of free memory that fits the requested size despite having enough total free memory. This is often due to the allocation and deallocation of objects of various sizes, leading to 'holes' in the memory. A lot of heterogeneity in the lifespans of objects (extremely common in real-world applications) can exacerbate the issue. The Python process grows over time, and people who haven't debugged it before are sure it's a memory leak. Once you are experiencing memory fragmentation, some of your techniques can help slow it down. The ultimate solution is generally to somehow create a separate memory pool for the problematic allocations - the easiest way is to allocate, aggregate, and deallocate them in a separate, short-lived process. So, the first thing anyone needs to do is figure out, "Do I NEED to optimize memory use?". The answer is often no, but in long-running app processes, systems engineering, and embedded engineering, it will be yes more often. More on reddit.com
🌐 r/Python
31
107
January 15, 2024
🌐
AppSignal
blog.appsignal.com › 2025 › 05 › 28 › ways-to-optimize-your-code-in-python.html
Ways to Optimize Your Code in Python | AppSignal Blog
May 28, 2025 - This section describes code optimization by avoiding global variables, using class encapsulation, and managing a namespace correctly. Local variables are faster to access compared to global variables, primarily due to the way Python manages ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › optimization-tips-python-code
Optimization Tips for Python Code - GeeksforGeeks
August 19, 2025 - n = [1, 2, 3, 4, 5] # Inefficient: manual loop + append s = [] for num in n: s.append(num ** 2) print("Inefficient:", s) # Optimized: list comprehension s = [num ** 2 for num in n] print("Optimized:", s) ... First method uses explicit looping with append() while the second is more concise and efficient. Using a list comprehension reduces overhead, resulting in faster execution and cleaner code. Local variables are faster because Python doesn’t need to search the global scope each time.
🌐
Stackify
stackify.com › how-to-optimize-python-code
Best Method of Python Code Optimization - Stackify - Ivanov
September 16, 2023 - For example, you can write something ... over again and thereby reducing the software performance. The result of the Peephole optimization technique is that Python pre-calculates constant expressions 60*60*24, replacing them with ...
🌐
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.
🌐
Real Python
realpython.com › linear-programming-python
Hands-On Linear Programming: Optimization With Python – Real Python
June 16, 2023 - Note: String representations are built by defining the special method .__repr__(). For more details about .__repr__(), check out Pythonic OOP String Conversion: __repr__ vs __str__ or When Should You Use .__repr__() vs .__str__() in Python?. Finally, you’re ready to solve the problem. You can do that by calling .solve() on your model object. If you want to use the default solver (CBC), then you don’t need to pass any arguments: ... .solve() calls the underlying solver, modifies the model object, and returns the integer status of the solution, which will be 1 if the optimum is found. For the rest of the status codes, see LpStatus[].
Find elsewhere
🌐
Medium
medium.com › @quanticascience › performance-optimization-in-python-e8a497cdaf11
Performance Optimization in Python | by QuanticaScience | Medium
February 24, 2024 - Profiling and debugging are essential practices for identifying and resolving performance bottlenecks in Python code. Concurrency and parallelism, through multi-threading, multi-processing, or asyncio, can greatly enhance the performance of ...
🌐
Python
python.org › doc › essays › list2str
Python Patterns - An Optimization Anecdote | Python.org
Try to use map(), filter() or reduce() to replace an explicit for loop, but only if you can use a built-in function: map with a built-in function beats for loop, but a for loop with in-line code beats map with a lambda function!
🌐
KDnuggets
kdnuggets.com › how-to-optimize-your-python-code-even-if-youre-a-beginner
How to Optimize Your Python Code Even If You’re a Beginner - KDnuggets
In this article, we'll walk through five practical beginner-friendly optimization techniques together. For each one, I'll show you the "before" code (the way many beginners write it), the "after" code (the optimized version), and explain exactly why the improvement works and how much faster it gets. ... Let's start with something you probably do all the time: creating new lists by transforming existing ones. Most beginners reach for a for loop, but Python has a much faster way to do this.
🌐
Duke University
people.duke.edu › ~ccc14 › sta-663 › MakingCodeFast.html
Code Optimization — Computational Statistics in Python 0.1 documentation
Profiling means to time your code so as to identify bottelnecks. If one function is taking up 99% of the time in your program, it is sensiblt to focus on optimizign that function first.
🌐
Plain English
python.plainenglish.io › 9-python-code-optimization-techniques-for-developers-6541ff397219
9 Python Code Optimization Techniques For Developers | by Pralabh Saxena | Python in Plain English
June 28, 2023 - In this article, we will explore several code optimization techniques. We will cover a range of techniques, from basic best practices to more advanced concepts such as using built-in functions, optimizing loops and leveraging Python’s standard library.
🌐
SOFTFORMANCE
softformance.com › home › blog › 25 tips for optimizing python performance
Optimizing Python Code for Performance: Tips & Tricks | SoftFormance
January 10, 2024 - Some of the techniques for improving Python code performance include concatenating strings with join, applying multiple assignments, using generators as keys for sorting, interning strings, and using the built-in “timeit” module.
🌐
Analytics Vidhya
analyticsvidhya.com › home › optimize python code for high-speed execution
Optimize Python Code for High-Speed Execution - Analytics Vidhya
May 28, 2025 - To optimize I/O operations, minimize the number of I/O calls, and use efficient I/O methods. Techniques such as buffering, asynchronous I/O, and batch processing can improve the performance of I/O-bound tasks.
🌐
Codefinity
codefinity.com › blog › Achieving-Peak-Performance-with-Python-Using-Optimization-Techniques
Achieving Peak Performance with Python Using Optimization Techniques
Learn how to optimize your Python code for better performance and efficiency by understanding Python's performance characteristics, profiling tools like cProfile, optimization techniques such as efficient data structures and algorithm selection, and ...
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().

🌐
Binmile
binmile.com › blog › python-performance-optimization
Performance Optimization in Python: Tools & Techniques [2025 Guide]
February 10, 2025 - Profiling: Use Python’s built-in modules like cProfile and timeit to identify bottlenecks and optimize critical parts of the code. Memoization and Caching: By caching expensive function calls and using memoization techniques, you can significantly reduce redundant computations.
Address   2803 Philadelphia Pike, Suite B 191, 19703, Claymont
🌐
HackerNoon
hackernoon.com › python-code-optimization-tips-for-developers-6vjjw3zjq
Python Code Optimization Tips For Developers | HackerNoon
August 13, 2019 - Optimization of Python codes deals with selecting the best option among a number of possible options that are feasible to use for developers. Python is the most popular, dynamic, versatile, and one of the most sought after languages for web ...
🌐
Python.org
discuss.python.org › python help
Python code optimization - Python Help - Discussions on Python.org
April 1, 2024 - Hi! I’m writing a Python program to determine if a number n is abundant, that is, if its factors (excluding itself) have a sum greater than n. I know you can just use from sympy import divisors n = int(input()) if sum…
🌐
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....