Boost Python Speed: 4 Simple Tricks to Cut Execution Time by Up to 20%
This article presents four practical Python techniques—including list reversal, variable swapping, in‑function looping, and reducing function calls—that together can shave roughly 10‑20% off your script's execution time.
Today I want to share four time‑saving Python tricks that can reduce execution time by about 10‑20%.
Reversing a list
Python offers two ways to reverse a list: slicing or the reverse() method. The built‑in reverse() modifies the original list, while slicing creates a new list.
Performance test shows reverse() is faster (≈10.7 µs per loop) than slicing (≈15.6 µs per loop).
Swapping two values
You can swap two variables in a single line without a temporary variable: variable_1, variable_2 = variable_2, variable_1 The same technique works for dictionary entries, reducing iteration and data‑conversion overhead.
Looping inside a function
Placing a for loop inside a function means the function is called only once, which can be slightly faster than calling the function repeatedly in an outer loop.
Reducing function calls
When checking an object’s type, isinstance() is the most efficient, followed by id() and type(). Avoid placing repeated operations in loop conditions; compute them once before the loop.
# Check if num is an int type
type(num) == type(0) # three function calls
type(num) is type(0) # two function calls
isinstance(num, int) # one function callImport specific objects directly (e.g., from X import Y) instead of importing the whole module, which saves a lookup.
In summary, extensive use of Python’s built‑in functions can speed up programs while keeping code concise and readable.
For more details, see the Python built‑in functions reference.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
