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
🌐
DataCamp
datacamp.com › tutorial › optimization-in-python
Optimization in Python: Techniques, Packages, and Best Practices | DataCamp
August 31, 2024 - In this section, we’ll cover optimization techniques commonly implemented in Python, including gradient descent, Newton’s method, conjugate gradient method, quasi-Newton methods, the Simplex method, and trust-region methods.
🌐
SciPy
docs.scipy.org › doc › scipy › tutorial › optimize.html
Optimization (scipy.optimize) — SciPy v1.17.0 Manual
Note that the Rosenbrock function and its derivatives are included in scipy.optimize. The implementations shown in the following sections provide examples of how to define an objective function as well as its jacobian and hessian functions. Objective functions in scipy.optimize expect a numpy array as their first parameter which is to be optimized and must return a float value.
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
Optimization Techniques in Python - Stack Overflow
Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more 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
Code Optimization in Your Projects
Decide if it’s worth optimizing. Run your code through a profiler Optimize the slowest parts until it’s acceptable Network is usually the slowest, and in Python specifically doing a lot of numerical calculations in a loop should be done in numpy, not in pure Python. But the most important rule is the first one. Usually the speed is ok but developer time is more expensive. More on reddit.com
🌐 r/Python
77
160
November 12, 2023
🌐
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.
🌐
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?

🌐
Stackify
stackify.com › how-to-optimize-python-code
Best Method of Python Code Optimization - Stackify - Ivanov
September 16, 2023 - Initially the code is written to a standard file, then you can run the command “python -m compileall <filename>”and get the same file in *.pyc format which is the result of the optimization. <Peephole> is a code optimization technique in Python that is done at compile time to improve your code performance.
🌐
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. In later examples I also use the timeit module, which is new in Python 2.3.
🌐
Google
developers.google.com › or-tools › get started with or-tools for python
Get Started with OR-Tools for Python | Google for Developers
OR-Tools for Python helps find the best solution to a problem by defining an objective and constraints. The library provides solvers for various optimization problems, including linear optimization, mixed-integer programming, constraint programming, ...
Find elsewhere
Top answer
1 of 9
11

As I said in comment, you must start by finding what part of your code is slow.

Nobody can help you without this information.

You can profile your code with the Python profilers then go back to us with the result.

If it's a Web app, the first suspect is generally the database. If it's a calculus intensive GUI app, then look first at the calculations algo first.

But remember that perf issues car be highly unintuitive and therefor, an objective assessment is the only way to go.

2 of 9
6

ok, not entirely to the point, but before you go and start fixing it, make sure everyone understands the situation. it seems to me that they're putting some pressure on you to fix the "problem".

well first of all, when you wrote the application, have they specified the performance requirements? did they tell you that they need operation X to take less than Y secs to complete? Did they specify how many concurrent users must be supported without penalty to the performance? If not, then tell them to back off and that it is iteration (phase, stage, whatever) one of the deployment, and the main goal was the functionality and testing. phase two is performance improvements. let them (with your help obviously) come up with some non functional requirements for the performance of your system.

by doing all this, a) you'll remove the pressure applied by the finance team (and i know they can be a real pain in the bum) b) both you and your clients will have a clear idea of what you mean by "performance" c) you'll have a base that you can measure your progress and most importantly d) you'll have some agreed time to implement/fix the performance issues.

PS. that aside, look at the indexing... :)

🌐
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
July 14, 2025 - 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.
🌐
Apmonitor
apmonitor.com › che263 › index.php › Main › PythonOptimization
Optimization with Python | Learn Programming
Optimization deals with selecting the best option among a number of possible choices that are feasible or don't violate constraints. Python can be used to optimize parameters in a model to best fit data, increase profitability of a potential engineering design, or meet some other type of objective that can be described mathematically with variables and equations.
🌐
Medium
medium.com › @quanticascience › performance-optimization-in-python-e8a497cdaf11
Performance Optimization in Python | by QuanticaScience | Medium
February 24, 2024 - Concurrency and parallelism, through multi-threading, multi-processing, or asyncio, can greatly enhance the performance of Python applications. Advanced techniques, including caching, memoization, and using Cython or slots, can provide significant ...
🌐
DEV Community
dev.to › jamesbright › 10-python-programming-optimisation-techniques-5ckf
10 Python programming optimisation techniques. - DEV Community
September 24, 2024 - NumPy (Numerical Python) is a popular Python library used for numerical and scientific computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. It can be installed with pip by running pip install numpy. Vectorisation eliminates the need for explicit loops, leveraging low-level optimisations for faster execution. By applying these techniques, you can ensure your Python or other programming language programs run faster, use less memory, and are more scalable, which is especially important for applications in data science, web and systems programming.
🌐
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…
🌐
SOFTFORMANCE
softformance.com › home › blog › 25 tips for optimizing python performance
Optimizing Python Code for Performance: Tips & Tricks | SoftFormance
January 10, 2024 - Run the command line script, activate ... and use Python’s “-m” option. Using generators is one more way to optimize memory consumption. These generators can yield items one by one instead of yielding them all at once. When you are sorting items in a list afterwards, we advise you to employ keys and the default <sort()> method. The developers can employ this technique to sort both ...
🌐
Python
python.org › doc › essays › list2str
Python Patterns - An Optimization Anecdote | Python.org
This is because local variable lookups are much faster than global or built-in variable lookups: the Python "compiler" optimizes most function bodies so that for local variables, no dictionary lookup is necessary, but a simple array indexing operation is sufficient.
🌐
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.
🌐
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 ...
🌐
SciPy
docs.scipy.org › doc › scipy › reference › optimize.html
Optimization and root finding (scipy.optimize) — SciPy v1.17.0 Manual
It includes solvers for nonlinear problems (with support for both local and global optimization algorithms), linear programming, constrained and nonlinear least-squares, root finding, and curve fitting.
🌐
HackerNoon
hackernoon.com › elevate-your-python-advanced-techniques-for-code-optimization
Elevate Your Python: Advanced Techniques for Code Optimization | HackerNoon
July 2, 2024 - Elevate your code optimisation techniques. Explore profiling, JIT compilation, concurrency, and more to enhance your code's performance and efficiency.
🌐
Mobook
mobook.github.io › MO-book
Hands-On Mathematical Optimization with Python
We cannot provide a description for this page right now