Fundamentals 7 min read

Four Time‑Saving Python Tricks to Boost Execution Speed

This article presents four practical Python techniques—including list reversal, tuple swapping, loop placement, and function‑call reduction—that together can shave roughly 10‑20% off typical script execution times while keeping the code clear and maintainable.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Four Time‑Saving Python Tricks to Boost Execution Speed

In this article we share four concise Python tricks that can reduce execution time by about 10‑20%.

Reversing a List

Python provides two ways to reverse a list: slicing ( mylist[::-1] ) and the in‑place reverse() method. The former creates a new list, while the latter mutates the original. Benchmarks using timeit show that reverse() 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>

The built‑in reverse() method modifies the original list and is noticeably faster than the slicing approach.

Swapping 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 one‑liner avoids extra assignments and can improve performance in tight loops.

Loop Inside a Function vs. Function Inside a Loop

Placing the for loop inside the function means the loop runs once, reducing the overhead of repeatedly calling the function.

<code>list_of_strings = ['apple','orange','banana','pineapple','grape']</code>
<code>def only_function(x):
    new_string = x.capitalize()
    out_putstring = 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>

Both functions produce the same output, but the version with the loop inside the function is slightly faster, as shown by the accompanying benchmark image.

Reducing Function Calls

When checking an object's type, isinstance() requires only one function call, whereas using type() or id() involves multiple calls.

<code># Check if num an int type
type(num) == type(0)  # Three function calls
type(num) is type(0)  # Two function calls
isinstance(num,(int)) # One function call</code>

Avoid placing expensive operations in loop conditions; compute them once before the loop.

<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 a specific object directly (e.g., from X import Y ) is faster than importing the whole module and accessing the attribute each time.

Conclusion

By leveraging Python’s built‑in functions and idiomatic patterns—such as in‑place list reversal, tuple unpacking for swaps, consolidating loops inside functions, and minimizing redundant function calls—you can noticeably speed up scripts while keeping the code clean and readable.

For further reading, consult the official Python documentation https://docs.python.org/3/library/functions.html and the reference images below.

performanceoptimizationlistSwapCodeLoop
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.