Optimising Code
Last updated
Last updated
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!
Using List Comprehensions
Instead of using loops to create or transform lists, use list comprehensions, which are more concise and often faster.
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.
Using Built-In Functions
Python's built-in functions are implemented in C and are highly optimised for performance.
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.
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.
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.
Using enumerate()
for Indexed Iteration
This technique avoids manual index management.
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.
Using any()
and all()
These functions are useful for checking conditions in a collection and are faster than manually looping through each element.