This repo is based on my article How to be fancy with Python. It includes small Python tricks that will make your life much much easier. I hope they also help you become a better Python programmer. It is available as a jupyter notebook so you can clone and run it yourself. Also, if you know some tricks of your own, submit a pull request and I'll be more than happy to include it.
TAB
to indent code
SHIFT + TAB
to unindent code
To comment a bunch of code, select it and press CONTROL + /
To surround something with quotation marks or brackets around something, press SHIFT + "
or SHIFT + (
Usually in Python, we loop over things like this:
To do the same with multiple lists, use zip
And if you need indexes by any chance you can just do
The best part about Python is that you can accomplish so much in so less code. Take list comprehensions for example. If you want to create a list of numbers in a certain range you can easily do it as follows:
You can also apply conditions on it very easily.
One practical example of this is to convert a number to its digits.
This concept of applying a function to every element of the list reminds me of map
Just like lists, there are comprehensions for dictionaries and generators as well. We'll talk about generators later.
Let's start with dictionaries. First let's learn about something called operator.itemgetter
. It retreives every element of the specified index.
Say you have a list of lists like this
and you want to get the first element of every inner list. You can do so as follows
Cool right?
Let me give you one more example. You can use it with the key
argument in the sorted function.
See how it works?
Okay back to dictionaries. A basic dictionary comprehension would be to map every element to an index.
A good practice for such dictionaries is to also create the reverse mapping. Trust me, you'll need it later.
We want to be able to do grouping in dictionaries like this:
Let's break that down. The first thing we need to do for this to work is sorting by grade
Then we can use itertools to group them
And finally create a comprehension in the format we need by choosing just the 0th element from every tuple, in this case, student name
Go over that one more time to make sure you understand it.
I bet those comprehensions were a lot to take in. Let's move onto lighter stuff for a while
The * operator can be used to repeat strings. For example
Now you probably don’t want to print “Python is cool” a whole lot of times but you should use it for something like this
The * operator can also be used to unpack iterables like lists
We can also use it with function arguments when we don't know the number of arguments in advance
*args
is used for variable number of arguments and **kwargs
is used for named arguments
Something else you can do with functions is create partial functions. What are they?
Suppose we have a function to calculate simple interest. We can set default values for some parameters (from right to left).
However, we cannot set the default value of just p in this way.
We can do so using a partial function. In a partial function, we set default values for some arguments, left to right and then use that as a function. Let’s set a default value for just p.
Although partials work from left to right, we can also skip parameters in between by using named arguments.
Partials are mainly used when you want to fix a few parameters and experiment with the rest.
Test driven development means you write tests and then you write code to pass those tests. You can write mini-tests in Python using assert.
For example, you might want to make sure the shape of a certain object is what you expect it to be.
You can also write a custom error message after a comma. Writing these mini-tests will be super helpful in making sure parts of your code work as expected. It will also help you debug things efficiently.
If you haven't already stopped using strings for paths, stop right now!
Check out this article for more examples and explanations.
We can use the yield keyword instead of return keyword in Python to create a generator. The advantage of using a generator is that is generates things on the fly and forgets them. This saves memory.
We can also create them using comprehensions
Proof that you can iterate over generators only once.
To search for 5 in nums it had to generate numbers from 0 to 5. Now it starts from 6.
If we want to know all the attributes and methods related to a particular object, we can use dir()
We can also check for attributes directly using hasattr
And we can check the type of a variable using isinstance. This is usually done to ensure the parameter passed to a function is of the correct type.
Those were some Python tricks that I believe would help everyone. Here's 2 more links for you. Keep learning.