CodeX
Published in

CodeX

5 magical tricks in Python to boost up your functions’ efficiency.

Simple and efficient.

Photo by Almos Bechtold on Unsplash

Introduction

Often whenever we work with Python applications, we work with a lot of dependencies. Python on its own isn’t individually good at anything, but it is only because of its wonderful packages that bring the functionality to the base.

Whenever someone takes a shot on this discussion, they often think of NumPy as an example. While matrix math might be possible with Python, utilizing NumPy makes it extensively better — and faster. Being said, often it seems Python developers do rely on external tools to process certain datatypes and work mathematically, Python does have some really cool tricks up its sleeve that do make it appeal to a scientific programming audience. Using these tricks you can keep your dependencies down, use less time, which generally makes programming a lot easier in Python! Next time you are thinking of installing something with Pip, you’ll be able to also consider the options available in the standard library!

DateTime

A great example of a tool that is quite common amongst scientific computing is a date-time type. It is common that data is going to have timestamps, at times timestamps are even the predictive piece that is going to be training our model. Being said that, working with dates and times might be an important concept for a Data Scientist. We can import the date-time module exactly how you might expect; it is common that this module is aliased as dt.

import datetime as dt

Now we can construct date-time types and work with date-time syntax and walk through properties like the year, month, and day. This is very useful for re-formatting, parsing, and working with individual sections of dates within your data. Let’s take a look at some basic functionality from this package:

import datetime as dt
now = dt.date.today()
print(now.year)
print(now.month)

Regular Expressions

Of all tools, the “re” module is far the most critically underrated. The “ R” and “ E” in re is short for Regular Expressions. The “re” module is used to parse strings with ‘re’ and provide more options for working with strings. How many times have you run into making algorithmic decisions based on functions that the string class has like str.split()? No more of that because regular expressions are far simpler, and a lot easier to use!

import re

The re module provides a lot of very useful functions especially for working with extensive amounts of data as Scientists typically do. Being said that, examples that will get you started are the sub() and find() functions.

import re
re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

Math

Math might not be the most comprehensive module in the history of the standard library in Python, but it does frequently come in handy. This function will be a very useful course even more true for scientific computing. The math module gives way to access everything from sin and cos all the way to logarithms. All of these can come in handy when working with algorithms, and many packages do depend on this basic module to get a lot of things done.

import math

The module can save some time by making mathematical operations easily available without dependencies. For example, we will be demonstrating the log() function, but you could most certainly look further into this module and find a whole world of mathematical capabilities!

import math
math.log(1024, 2)

Statistics

Another package that is obviously for scientific computing is the statistics module. This module provides some primary statistics that might not go as in-depth as something like SciPy, but can still answer quite frequently for data analysis. While inferential and Bayesian statistics might not be a principal focus of this package, mathematical values such as the mean, the standard deviation can tell a lot about the data that you might be working with. I alias this module as st.

import statistics as st

There are plenty of useful functions provided by this module that are certainly worth checking out! The great thing about this package is that it will always be there, whether you need it or not, and it won’t require any dependencies. Let’s look at some basic general-purpose statistical operations that are easily provided with this package:

import statistics as st
st.mean(data)
st.median(data)st.variance(data)

Lambda Functions

Lambda functions ‘anonymous’ functions. This basically means you can quickly make functions without needing to properly define a function using Python’s def.

Lambda functions are created to make your function to be very short, that is to write your function in a single line. For more complex logic you will need to use regular functions.

I will now show you an example. this example is all about squaring the number. Have a look at the one-liner.

# lambda function
square = lambda x: x ** 2
print('square lambda: {}'.format(square(4)))>>> square lambda: 16

Conclusion

Often in Pythonic programming, seems like there is a high reliance on dependencies, the Python standard library also has some pretty cool tools in it! A lot of these tools can quickly be used to save an ample amount of time by making a high-level interface for complex tasks that are packaged with the programming language itself. This can be used to minimize dependent packages, virtual environments, and general clutter around a server. Therefore, there is no need to pip install any packages, so a lot of time is saved with this initiative.

Don’t forget to leave your responses.✌

Everyone stay tuned!! To get my stories in your mail box kindly subscribe to my news letter.

Thank you for reading! Do not forget to give your claps and to share your responses and share it with a friend!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store