10 Smooth Python Tricks For Python Gods | by Emmett Boudreau | Towards Data Science

Although on the surface Python might appear to be a language of simplicity that anyone can learn, and it is, many might be surprised to know just how much mastery one can obtain in the language. Python is one of those things that is rather easy learn, but can be difficult to master. In Python, there are often multiple ways of doing things, but it can be easy to do the wrong thing, or reinvent the standard library and waste time simply because you were not aware of a module’s existence.
Unfortunately, the Python standard library is quite a vast beast, and furthermore, its ecosystem is absolutely terrifyingly enormous. Although there are probably two-million gigabytes of Python modules, there are some useful tips that you can learn with the standard library and packages usually associated with scientific computing in Python.
Though it might seem rather basic, reversing a string with char looping can be rather tedious and annoying. Fortunately, Python includes an easy built-in operation to perform exactly this task. To do this, we simply access the indice ::-1 on our string.
a = "!dlrow olleH"backward = a[::-1]
In most languages, in order to get an array into a set of variables we would need to either loop through the values iteratively or access the dims by position like so:
firstdim = array[1]
In Python, however, there is a way cooler and quicker way to do so. In order to change a list of values into variables we can simply set variable names equal to the array with the same length of the array:
array = [5, 10, 15, 20]five, ten, fift, twent = array
If you’re going to spend any time whatsoever in Python, you will definitely want to get familiar with itertools. Itertools is a module within the standard library that will allow you to get around iteration constantly. Not only does it make it far easier to code complex loops, it also makes your code both faster and more concise. Here is just one example of a use for Itertools, but there are hundreds:
c = [[1, 2], [3, 4], [5, 6]]# Let's convert this matrix to a 1 dimensional list.import itertools as itnewlist = list(it.chain.from_iterable(c))
Unpacking values iteratively can be rather intensive and time consuming. Fortunately, Python has several cool ways in which we can unpack lists! One example of this is the *, which will fill in unassigned values and add them to a new list under our variable name.
a, *b, c = [1, 2, 3, 4, 5]
If you’re not aware of enumerate, you probably should get familiar with it. Enumerate will allow you to get indexes of certain values in a list. This is especially useful in data science when working with arrays rather than data-frames.
for i,w in enumerate(array):    print(i,w)
Slicing apart lists in Python is incredibly easy! There are all sorts of great tools that can be used for this, but one that certainly is valuable is the ability to name slices of your list. This is especially useful for linear algebra in Python.
a = [0, 1, 2, 3, 4, 5]LASTTHREE = slice(-3, None)slice(-3, None, None)print(a[LASTTHREE])
Grouping adjacent loops could certainly be done rather easily in a for loop, especially by using zip(), but this is certainly not the best way of doing things. To make things a bit easier and faster, we can write a lambda expression with zip that will group our adjacent lists like so:
a = [1, 2, 3, 4, 5, 6]  group_adjacent = lambda a, k: zip(*([iter(a)] * k)) group_adjacent(a, 3) [(1, 2, 3), (4, 5, 6)] group_adjacent(a, 2) [(1, 2), (3, 4), (5, 6)] group_adjacent(a, 1)
In most normal scenarios in programming, we can access an indice and get our position number by using a counter, which will just be a value that is added to:
array1 = [5, 10, 15, 20]array2 = (x ** 2 for x in range(10))counter = 0for i in array1:# This code wouldn't work because 'i' is not in array2.   # i = array2[i]    i = array2[counter]#    ^^^ This code would because we are accessing the position of i
Instead of this, however, we can use next(). Next takes an iterator that will store our current position in memory and will iterate across our list in the background.
g = (x ** 2 for x in range(10))print(next(g))print(next(g))
Another great module from the standard library is collections, and what I would like to introduce to you today is Counter from collections. Using Counter, we can easily get counts of a list. This is useful for getting the total number of values in our data, getting a null count of our data, and seeing the unique values of our data. I know what you’re thinking,
“ Why not just use Pandas?”
And this is certainly a valid point. However, using Pandas for this is certainly going to be a lot harder to automate, and is just another dependency you are going to need to add to your virtual environment whenever you deploy your algorithm. Additionally, a counter type in Python has a lot of features that Pandas Series don’t have, which can make it far more useful for certain situations.
A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7]) A Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1}) A.most_common(1) [(3, 4)] A.most_common(3) [(3, 4), (1, 2), (2, 2)]
Another great thing coming out of the collections module is dequeue. Check out all the neat things we can do with this type!
import collectionsQ = collections.deque() Q.append(1) Q.appendleft(2) Q.extend([3, 4]) Q.extendleft([5, 6]) Q.pop()Q.popleft()Q.rotate(3) Q.rotate(-3)print(Q)
So there you have it, these are some of my favorite Python tricks that I use all the time. Though some of these might be used a little more rarely, these tricks tend to be very versatile and useful. Fortunately, the Python tool-box of standard library functions certainly doesn’t start to become bare there, and there are certainly more tools inside of it. More than likely there are some that I don’t even know, so there’s always something to learn which is exciting!