Python tricks I wish I knew earlier

Manpreet Singh
3 min readAug 18, 2021

Welcome back! Python is one of my favorite programming languages out there, so let’s take a look at some Python tricks I wish I had known earlier. Now, these tricks range from actual functions within Python all the way to tricks to speed up your Python code! With that long introduction out of the way, let’s get into it!

Getting Random Data

First up, let’s take a look at getting random data from a dataset. Let’s use the list that we created earlier for this example, if we wanted to get a random selection of data from this list we can use the sample function:

Creating the list with this line:

set1 = [ 1, 2, 3, 4, 5 ]

Using the random.sample function with this list with 2 random samples:

random.sample(set1, 2)

Few things to note, the set1 in the code is the name of the dataset, the number 2 is the number of random samples from this dataset, the output for us in this example is this:

Changing Your While Loops

Another interesting way to speed up your Python code is within your whileloops, there are times where you may use the following line:

while True:
#code down here

A faster way to write an infinite loop is by using 1 instead of True:

while 1:
#code down here

Exchanging Variables

There may come a time in your Python project where you have to exchange one variable for another, there are a few different ways this can be done, but let’s do it in one line of code! Let’s use the set data sets we used before:

set1 = [ 1, 2, 3, 4, 5 ]set2 = [ 3, 4, 5, 6, 7 ]

In order to exchange these variables for one another, you have to equal these lists as the opposite of one another, here is exactly how to do this:

set1, set2 = set2, set1

You will now see that both the variables have been exchanged for one another!

Loading Packages As You Need Them

Another effective way to speed up the processing time of your Python application is by loading…

--

--