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

--

--