Four Python Tricks to Speed Up Execution by 10–20%
This article presents four practical Python performance tricks—list reversal, variable swapping, in‑function looping, and reducing function calls—demonstrating how each can shave 10‑20% off execution time with clear code examples and timing benchmarks.
Today we share four time‑saving Python tricks that can reduce execution time by roughly 10–20%.
Reverse a List
Python offers two ways to reverse a list: slicing (e.g., mylist[::-1] ) and the reverse() method. The former creates a new list, while the latter modifies the original in place.
Benchmarking with timeit shows the reverse() method is faster:
<code>$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist[::-1]'
1000000 loops, best of 5: 15.6 usec per loop
</code> <code>$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist.reverse()'
1000000 loops, best of 5: 10.7 usec per loop
</code>Thus, reverse() is the more efficient choice.
Swap Two Values
Python allows swapping two variables in a single line without a temporary variable:
<code>variable_1 = 100
variable_2 = 500
</code> <code>variable_1, variable_2 = variable_2, variable_1
</code>The same technique works for dictionary entries:
<code>md[key_2], md[key_1] = md[key_1], md[key_2]
</code>This reduces the number of operations and speeds up the code.
Loop Inside a Function
Placing the loop inside the function avoids repeated function calls during iteration. Two equivalent functions are shown—one that only processes a single element and another that loops internally.
<code>list_of_strings = ['apple','orange','banana','pineapple','grape']
</code> <code>def only_function(x):
new_string = x.capitalize()
output_string = x + " " + new_string
print(output_string)
</code> <code>def for_in_function(listofstrings):
for x in list_of_strings:
new_string = x.capitalize()
output_string = x + " " + new_string
print(output_string)
</code>Running the in‑function loop is slightly faster, as demonstrated by the accompanying chart.
Reduce Function Call Overhead
When checking an object's type, prefer isinstance() (one call) over type() or id() (multiple calls):
<code># Check if num is an int type
type(num) == type(0) # three calls
type(num) is type(0) # two calls
isinstance(num, (int)) # one call
</code>Avoid placing expensive operations like len() inside loop conditions; compute them once beforehand:
<code># Each loop the len(a) will be called
while i < len(a):
statement
# Only execute len(a) once
m = len(a)
while i < m:
statement
</code>Importing directly with from X import Y also reduces lookup overhead compared to import X; X.Y .
In summary, leveraging Python’s built‑in functions and idiomatic patterns can noticeably improve performance while keeping code concise and readable.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.