You are on page 1of 7

8/16/22, 12:46 PM 5 Simple Techniques to Write Your Code More Efficiently in Python | by Chris Zita | Towards Data Science

Open in app Get started

Published in Towards Data Science

You have 2 free member-only stories left this month.


Sign up for Medium and get an extra one

Chris Zita Follow

Feb 26 · 5 min read · · Listen

Save

5 Simple Techniques to Write Your Code More


Efficiently in Python
Make your code faster, easier to read, and more understandable

Photo from Pexels by Cottonbro

Python is a powerful programming language that enables you to do a lot in a little


https://towardsdatascience.com/5-simple-techniques-to-write-your-code-more-efficiently-in-python-f095bb2b1e15 1/7
8/16/22, 12:46 PM 5 Simple Techniques to Write Your Code More Efficiently in Python | by Chris Zita | Towards Data Science

code.
Open in app Get started

However, with great power comes great responsibility.

In order to write efficient and optimized code, you need to avoid unnecessary uses of
code and use proper practices and techniques that will make your code run faster.

In this post, we will discuss 5 techniques that will help you write faster, more efficient
code in Python!

1. Creating Functions
A function is a block of code that can be called from anywhere in your program.

Functions are often used to perform repetitive tasks, such as calculating the area of a
circle or printing out text on screen. The simplest way to create one is by using def
keyword followed by its name and parentheses ():

def square(x):

return x*x

print(“The square of”, 25, “is”, square(25))

This code will print out: The square of 25 is 625.

Functions are a great way to organize your code and make it more readable. You can
also use them to hide implementation detail from the user of your code.

Rather than writing the same block of code again and again, use functions to write it
once and call it from multiple places. This will make your code more efficient and
easier to read and maintain.

2. Eliminate Unessential Operations


When writing code, try to eliminate any unessential operations. For example, if you are
looping through a list of items and only need the first item, don’t bother looping
through the rest of the list.

https://towardsdatascience.com/5-simple-techniques-to-write-your-code-more-efficiently-in-python-f095bb2b1e15 2/7
8/16/22, 12:46 PM 5 Simple Techniques to Write Your Code More Efficiently in Python | by Chris Zita | Towards Data Science

list = [0, 0, 0] Open in app Get started

for i in range(len(list)):

print(“The Squared value of”, i, “is”, list[i]*list[i])

This will print out: The squared value of 0 is 0.

To make your code more efficient is this example, you can use the index() method to
get the position of an element in a sequence and then stop when you find it by breaking
from your loop.

This code is more efficient because it is doing less work.

list = [0, 0, 0]

for i in range(len(list)):

if list[i] == 0:

break

print(“The Squared value of”, i, “is”, list[i]*list[i])

This code will print out the same thing as before (The squared value of 0 is 0) but the
difference is that it gets the same result in less time, as it does not go through the full
loop, it stops when we get what we need.

Other ways you can eliminate unessential operations include:

Using continue instead of break to skip over the rest of an iteration in a loop

Reuse variables when possible (e.g., don’t create new ones every time)

Use generators for large sequences or iterators that will be used multiple times; this
saves memory because it only loads one element at a time

3. Use Packages to Your Advantage


Python comes with a large number of packages that you can use to make your code
more dynamic and efficient.

Packages are collections of functions, classes and other tools that have been written by
https://towardsdatascience.com/5-simple-techniques-to-write-your-code-more-efficiently-in-python-f095bb2b1e15 3/7
g
8/16/22, 12:46 PM
,
5 Simple Techniques to Write Your Code More Efficiently in Python | by Chris Zita | Towards Data Science
y
other Python developers. They are stored in repositories called PyPI (Python Package
Get started Open in app

Index) and can be installed using the pip tool.

Packages can be used to do everything from parsing XML documents to creating


graphical user interfaces. You can find a list of all the packages that are installed on
your system by running the following command:

python -m pip freeze

This will print out a list of all the packages that are currently installed on your system,
along with their version numbers. You can also use this command to install new
packages.

For example, if you want to install the pandas package, you would run the following
command:

python -m pip install pandas

This will install the latest version of the pandas package from PyPI. You can also specify
a specific version number if you want to use a different version.

When looking for packages to solve a particular problem, it is often a good idea to
search the PyPI repository. You can do this by running the following command:

pypi -l

This will print out a list of all the packages that are available on PyPI, along with their
descriptions. You can also browse PyPI online at pypi.org.

4. Avoid Declaring Unnecessary Variables


When you are writing code, avoid declaring unnecessary variables. For example, if you
only need to use a value once don’t bother declaring a new variable to hold that value
https://towardsdatascience.com/5-simple-techniques-to-write-your-code-more-efficiently-in-python-f095bb2b1e15 4/7
8/16/22, 12:46 PM 5 Simple Techniques to Write Your Code More Efficiently in Python | by Chris Zita | Towards Data Science
only need to use a value once, don t bother declaring a new variable to hold that value.
Open in app Get started

This is what not to do:

x = 25

y = x*x

print(y)

This will print out the square of 25 which is 625. Here you can eliminate the need for a
variable by using the built-in functions pow() or square(). In this example, we will use
pow():

x = 25

print(pow(x,x))

This code will print out the same as before but now we only have 1 variable declared
not 2.

The simple reason why we don’t want extra variables is because they can make our
code difficult to read and maintain.

When you are looking at a block of code, it’s important to be able to quickly understand
what each variable is used for. If there are too many variables, this becomes difficult to
do.

5. Break Loops When Necessary


It is important to break out of loops when necessary. For example, consider this code:

while True:

print(“Hello World!”)

Thi ill i “H ll W ld!” f il kill h


https://towardsdatascience.com/5-simple-techniques-to-write-your-code-more-efficiently-in-python-f095bb2b1e15 ll ih 5/7
8/16/22, 12:46 PM 5 Simple Techniques to Write Your Code More Efficiently in Python | by Chris Zita | Towards Data Science
This will print out “Hello World!” forever, or until you kill the program manually with
Open
Ctrl-C. You can make it stop by using a break statement inside in app
of an Get started
if clause:

while True:

if some condition is met:

break

print(“Hello World!”)

This will print out “Hello World!” until some condition is met like if hello world is
printed 5 times then stop the code.

The same concept can be applied to for loops as well. For example, consider this code:

for i in range(0, 100):

if i % 15 == 0:

break

print(i)

This code will print out all of the numbers from 0 to 99, except for those that are
divisible by 15. When it reaches a number that is divisible by 15 the code will stop.

The break statement can be useful in many situations, such as when you want to exit a
loop early because some condition has been met or if an error occurs while running
your code.

Conclusion
These are just a few of the techniques that you can use to write more efficient code in
Python. There are many other things that you can do, such as using classes, organizing
your code into modules, and taking advantage of built-in functions. By following these
tips, you can write code that is easy to read and understand, and that runs faster.

Happy Coding!

Join my email list with 5k+ people to get “The Complete Python for Data Science
Cheat Sheet Booklet” for FREE

Thanks to Ben Huberman


https://towardsdatascience.com/5-simple-techniques-to-write-your-code-more-efficiently-in-python-f095bb2b1e15 6/7
8/16/22, 12:46 PM 5 Simple Techniques to Write Your Code More Efficiently in Python | by Chris Zita | Towards Data Science

Open in app Get started

Sign up for The Variable


By Towards Data Science

Every Thursday, the Variable delivers the very best of Towards Data Science: from hands-on tutorials and cutting-
edge research to original features you don't want to miss. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review
our Privacy Policy for more information about our privacy practices.

Get this newsletter

About Help Terms Privacy

Get the Medium app

https://towardsdatascience.com/5-simple-techniques-to-write-your-code-more-efficiently-in-python-f095bb2b1e15 7/7

You might also like