Optimising Code

It is important that when creating our code we are as efficient as possible. This not only saves time, but also saves storage and improves efficiency when running a program.

Look at the following for advice on how we can best optimise code - you may even find you come across functions you have not used before!

Code Practice
Unoptimised
Optimised

Using List Comprehensions

Instead of using loops to create or transform lists, use list comprehensions, which are more concise and often faster.

squares = [] 
for i in range(10): 
    squares.append(i * i)
squares = [i * i for i in range(10)]

Using Generator Expressions for Large Data

Generators are more memory-efficient than lists when dealing with large datasets because they generate items on the fly rather than storing them all in memory.

squares = [i * i for i in range(1000000)]
squares = (i * i for i in range(1000000))

Using Built-In Functions

Python's built-in functions are implemented in C and are highly optimised for performance.

total = 0 
for num in range(1, 1001): 
    total += num
total = sum(range(1, 1001))

Avoiding Unnecessary List Copying

When you slice a list, Python creates a new list object. To avoid unnecessary copying, work with the original list when possible.

new_list = my_list[:]
new_list = my_list

Avoiding Global Variables

Accessing global variables is slower than accessing local variables. It is often better to pass variables as arguments to functions instead of relying on global state.

x = 10 
def add_to_x(y): 
    return x + y
def add_to_x(x, y): 
    return x + y

Using join() for String Concatenation

Concatenating strings with + can be inefficient because it creates a new string object each time. Instead, use join() to concatenate a list of strings.

words = ["Hello", "world", "from", "Python"]
sentence = ""
for word in words:
    sentence += word + " "
words = ["Hello", "world", "from", "Python"]
sentence = " ".join(words)

Using enumerate() for Indexed Iteration

This technique avoids manual index management.

i = 0
for item in my_list:
    print(i, item)
    i += 1
for i, item in enumerate(my_list):
    print(i, item)

Minimising Function Calls in Loops

Repeated function calls in loops can slow down performance. Instead, store function results in a variable if they are called multiple times.

for i in range(len(my_list)):
    print(len(my_list))
list_length = len(my_list)
for i in range(list_length):
    print(list_length)

Using any() and all()

These functions are useful for checking conditions in a collection and are faster than manually looping through each element.

found = False
for item in my_list:
    if item > 10:
        found = True
        break
found = any(item > 10 for item in my_list)

Last updated