5 Cool Python Tricks

hugoestradas

Hugo Estrada S.

Posted on June 19, 2020

5 Cool Python Tricks

Alt Text

Python is an awesome programming language, specially for Data Analysis and Machine Learning.
I've worked with Python for a couple of years and some of its syntax is very different from other languages I've worked before, like JAVA or C#.

So here are some of the most useful tricks I've learned so far with Python:

Trick #1 - The Python Interactive Shell:
Python provides a Shell which is used to execute a single Python command and get the result. Python Shell waits for the input command from the user. As soon as the user enters the command, it executes and displays the result.

For this example I'm going to use a function in a file as it follows:

Alt Text

I'm using VIM, as you can see this function only adds two numbers.
Typically I'd run this program like this:

Alt Text

Now, there's an alternative way of running this program, with the Interactive Shell:

Alt Text

This is a very useful tool when coding in Python, it'll load the Python script or file and instead of closing it after running it, it will give you access to all the variables and functions inside.

Trick #2 - The Python Debugger:
While "python -i" will will run the entire Python script or file, then provide an interface into the environment, the PDB can stop this file before it's finished executing, so you can debug.

Take a look at this example:

Alt Text

This time I'm adding 1 and 3, and then adding 1 and 'three', where 'three' is a string instead of an integer.
So if I try to run this file as it is, it'll throw an error:

Alt Text

In this example, I'm using a very small file (less than 5 lines of code), but when using larger scripts this could cause problems, and detect inconsistencies will be a nightmare. Fortunately there's the PDB:

Alt Text

By importing the pdb and using the .set_trace() method before the line you're interested in debug, in the execution you'll get the PDB interface, where you print the current values of variables or functions, or go to the next line with the "n".

Alt Text

Trick #3 - The virtual Environment:

There's a reason why working with virtual environments is a best-practice in Python: Dependency Management.

One headache of Python is ironically one its best features, since Python has so many libraries for like every possible problem you could imagine, you'll soon find out that dealing with them is also a big challenge.

So dependency management with Python could be annoying, but one elegant way of dealing with it, is using virtual environments; the most popular one is Virtualenv:

Alt Text

To create a new virtual environment type "virtualenv" :

Alt Text

Then just activate the virtual environment:

Alt Text

You'll notice a prefix on the shell, that's the indicator that you're using a virtual environment.
Now you can install dependencies in isolation at need:

Alt Text

Trick #4 - List and Dict Comprehension:

Let's say you have some data in a list, with data of results of the Myers-Briggs personality test, with the names and total of percentages represented as a dict.

Alt Text

Often you'd like to pull out a single property from an object, to do that in conventional Python syntax you'll do something like this:

Alt Text

Alt Text

That get the job done, but also required 4 additional lines of code.

There's a more elegant way of doing this, in a single line of code, using list-comprehension:

Alt Text

We can do even more with list-comprehension, like adding conditional statements to the end:

Alt Text

Now, for the dist-comprehension example: Here we have a list where 'name' is the key and 'percentage' is the value.
Again, to show the list you would have to loop the entire list, but instead using dist-comprehension you con do it in a single line of code:

Alt Text

Alt Text

Trick #5 - Lambda Functions λ:

In a nutshell a lambda function is a small anonymous function that can take any number of arguments, but can only have one expression.

Let me show you what I'm talking about in this example creating a function called "add" and another function "add2" that has a lambda:

Alt Text

Running this script with the interactive shell, turns out these two are exactly the same:

Alt Text

In a practical scenario, if you have multi-line complex functions go for a "def" for sure.
But if you're defining a function withing the interactive shell use lambda:

Alt Text

So that's it... hope you'll find it useful (!)

💖 💪 🙅 🚩
hugoestradas
Hugo Estrada S.

Posted on June 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related