With the new coming around, what’s a better resolution to make than improving your Python programming skills!
If you’re a data scientist, this is still relevant. Python scripting is especially important when it comes to cleaning data, manipulating data, and feature engineering, so don’t take this lightly – time is money.
Although it is reasonably easy to pick up Python and learn the basics, getting better and more efficient at programming in Python is a constant learning curve. Luckily, there are several ways that you can improve and speed up your Python code, and that’s what we’ll explore in this article.
With that said, here are five ways to improve your Python code:
1. Import Libraries and Use Built-In Functions
One of the greatest advantages of Python as a programming language is that it has a huge community of developers who create libraries and packages that can be imported into your development environment. Pre-made libraries and packages can provide you with hundreds of new functions which can save you many hours of work. For example, if you’re not already using NumPy for mathematical calculations and Data Science, it’s a good idea to import it and learn the basic functions.
Python also has a number of built-in functions that are also meant to save you time. Just as an example, here is how the map() function can save you tons of time when you are applying a function to iterables in a Python list.
Before using the map() function:
ages = [23, 42, 66, 14]
childOrAdult = []
for age in ages:
if age > 18:
childOrAdult.append("Adult")
else:
childOrNot.append("Child")
return childOrAdult
After using the map() function.
ages = [23, 42, 66, 14]
def childOrAdult(n):
return "Child" if n < 18 else "Adult"
Functions like these make it so much easier to perform these kinds of operations with much more flexibility and less code!
2. List Comprehensions
Lists in Python are typically created by declaring the variables one by one, appending and removing entries, etc. However, there is a less commonly used way of creating lists that saves you a few coding seconds every time you use it, with the additional benefit that you’ll make a tiny decrease in computing time. It’s called list comprehensions, and they allow you to declare a list with appropriate variables, all in one line, without using a for loop.
It is so extremely straightforward that the only explanation needed is a before vs after.
Before using list comprehensions:
numbers = []
for i in range(0,10):
numbers.append(i)
return numbers
After list comprehension:
numbers = [i for i in range(0,10)]
return numbers
Yes, I know that feels like cheating, but you really can just put your simple loops inside the list declaration and call it a day. There’s nothing wrong with it and it’ll generate exactly the same list, just without the extra lines of code.
3. Ternary Conditionals
Did you know that there is an easy and intuitive way to simplify your if – else statements in Python? Normally these sections take up a handful of lines and waste typing time which could be better spent working on important parts of your code. The way you shorten simple if – else conditions into single line pieces of code is through ternary conditionals.
Let’s see how it works. Here is our if – else statement initially:
a = 1
if a == 1:
b = 2
else:
b == 3
return b
However, this code isn’t good and it isn’t concise! We can write it more simply like the following:
b = 2 if a == 1 else b = 3
That line will work in practically every modern version of Python. I believe ternary conditionals were first added into Python in version 2.5.
4. Format Strings with Python F-Strings
Have you ever created some kind of dialogue to be printed out on your Python console and wanted to include a variety of variables in it? Well, such a simple task can get fairly tricky and time-consuming if you have a lot of variables, but there’s a faster and more efficient way to perform this task.
The method is through using Python F-strings. There are actually three types of F-strings available in Python, and they all work to help format your strings with variables. It saves you having to convert each variable to the right type before your print statement, and it allows you to more intuitively write the text inside print(). It’s easier to understand how this works by looking at the code.
Here is what your print statement might look like with several variables and a print statement when you are not using F-strings:
name = "Jeff"
age = 30
print("My name is ", name, " and I am " str(age), " years old.")
That code is ugly, takes long to write and all in all not very convenient for anyone. I understand that many people have been using this method for years, and beginners especially are the most common users of this conventional technique. However, look how better it is with F-strings:
name = "Jeff"
age = 30
print("My name is {name} and I am {age} years old.").format(name=name, age=age)
Not only was this F-string about three times faster for me to type out, but it is also far more intuitive, makes more sense at a glance, and allows faster and more convenient editing. There are various more benefits of F-strings that you should explore yourself.
5. Lambda Functions
What are lambda functions, you ask? Not many beginner programmers looking to clean up their code and become more efficient in Python actually discover lambda functions, and they’re missing out. A lambda is effectively a tiny function, a little unit, which has a single output and can be run again and again with very minimal lines of code.
As usual, let’s see our before vs after for how a lambda can improve your code:
# Before
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (13, 25, 36)
F = map(fahrenheit, temp)
C = map(celsius, F)
#After
>>> Celsius = [13, 25, 36]
>>> Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
>>> C = map(lambda x: (float(5)/9)*(x-32), Fahrenheit)
Notice how when we used lambda, we didn’t have to define the fahrenheit(T) or the celsius(T) functions.
The lambda acts kind of like a variable, but don’t be fooled – it’s definitely a function. You can save yourself a few lines of code with this, and it is recommendable to use lambda functions for those little operations you find yourself repeating over and over again in your program!
Thanks for Reading!
I hope you had as much fun reading this as I did writing this! Hopefully, you learned a couple of things, like new data visualization techniques or what makes a good visualization. Let me know what your favorite data visualization from 2020 is in the comments.
Terence Shin
- If you enjoyed this, follow me on Medium for more
- Sign up for my email list here!
- Let’s connect on LinkedIn
- Interested in collaborating? Check out my website.