Python Best Practices Tips and Tricks
Python Best Practices Tips and Tricks
towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5
May 3, 2020
Photo by author
Here are 30 Python best practices, tips, and tricks. I’m sure they’ll help you
procrastinate your actual work, and still learn something useful in the process.
1. Use Python 3
In case you missed it: Python 2 is officially not supported as of January 1, 2020.
This guide has a bunch of examples that only work in Python 3. If you’re still on Python
2.7, upgrade now.
3. Use IPython
1/12
Screenshot by author
IPython is basically an enhanced shell. It’s worth it just for the autocompletion alone,
but there is much more. I like it too for all the magic commands that are built-in. Here
are a few :
Another useful feature is referencing the output of a previous command.In and Out are
actual objects. You can use the output of the 3rd command by using Out[3] .
2/12
4. List Comprehensions
A list comprehension can replace ugly for loops used to fill a list. The basic syntax for a
list comprehension is:
And because you can use an expression, you can also do some math:
And finally, you can use the ‘if’ to filter the list. In this case, we only keep the values that
are dividable by 2:
It’s because the range function returns a class thatonly behaves like a list. A range is a
lot more memory efficient than using an actual list of numbers.
You can see for yourself by using a list comprehension to create an actual list of
numbers from the same range:
This is alright for a limited number of return values. But anything past 3 values should
be put into a (data) class.
3/12
you can easily print a data class for debugging because __repr__ is implemented
you can easily print a data class for debugging because __repr__ is implemented
as well
data classes require type hints, reduced the chances of bugs
If there are overlapping keys, the keys from the first dictionary will be overwritten.
To split on whitespace, you actually don’t have to give split any arguments. By default,
all runs of consecutive whitespace are regarded as a single whitespace separator by
split . So we could just as well use mystring.split() .
If you were wondering why it’s not mylist.join(" ") — good question!
It comes down to the fact that the String.join() function can join not just lists, but any
iterable. Putting it inside String prevents implementing the same functionality in multiple
places.
4/12
13. Emoji
This one will either impress or repulse, depending on who’s looking. On a more serious
note, this can come in handy especially when analyzing social media data.
Visit the emoji package page for more examples and documentation.
a[start:stop:step]
Start , stop and step are optional. If you don’t fill them in, they will default to:
0 for start
the end of the string for end
1 for step
5/12
Here are some examples:
You can use the following code to display the image from your Python code:
6/12
It’s me, looking at kittens
Pillow can do a lot more than displaying the image. It can analyze, resize, filter,
enhance, morph, etcetera. See the documentation for all its features.
map(function, something_iterable)
So you give it a function to execute, and something to execute on. This can be anything
that’s iterable. In the examples below I’ll use a list.
Take a look at your own code and see if you can use map() instead of a loop
somewhere!
7/12
18. Get unique elements from a list or string
By creating a set with the set() function, you get all the unique elements from a list or
list-like object:
Do you understand why this works? Try to figure it out for yourself before reading on.
max() will return the highest value in a list. The key argument takes a single
argument function to customize the sort order, in this case, it’s test.count. The
function is applied to each item on the iterable.
test.count is a built-in function of list. It takes an argument and will count the
number of occurrences for that argument. So test.count(1) will return 2 and
test.count(4) returns 4.
set(test) returns all the unique values from test, so {1, 2, 3, 4}
So what we do in this single line of code is take all the unique values of test, which is
{1, 2, 3, 4} . Next, max will apply the list.count function to them and return the
maximum value.
You can obtain the result of the last expression with the underscore operator, e.g. in
8/12
You can obtain the result of the last expression with the underscore operator, e.g. in
IPython this looks like:
In [1]: 3 * 3
Out[1]: 9In [2]: _ + 3
Out[2]: 12
This works in the Python shell too. In addition, the IPython shell allows you to use
Out[n] to get the value of the expression In[n] . E.g., Out[1] would give us the
number 9 in the example above.
python3 -m http.server
This is useful if you want to share some stuff with a co-worker or want to test a simple
HTML site.
I prefer the second way, which concatenates multiple lines together, allowing you to
format your code nicely. The only downside is that you need to explicitly put in
newlines.
As an example:
9/12
You can use Counter from the collections library to get a dictionary with counts of all the
You can use Counter from the collections library to get a dictionary with counts of all the
unique elements in a list:
You can do so much cool stuff with this library. I’ll limit the examples to just this one that
I found particularly useful: fuzzy parsing of dates from log files and such.
Just remember: where the regular Python datetime functionality ends, python-dateutil
comes in!
10/12
By Torindkflt — Public Domain
In Python 2, the division operator ( / ) defaults to an integer division, unless one of the
operands is a floating-point number. So you have this behavior:
# Python 2
5/2=2
5 / 2.0 = 2.5
In Python 3, the division operator defaults to a floating-point division and the // operator
has become an integer division. So we get:
Python 3
5 / 2 = 2.5
5 // 2 = 2
For the complete motivation behind this change, you should read PEP-0238.
11/12
You now have an extra command-line tool called chardetect, which can be used like
You now have an extra command-line tool called chardetect, which can be used like
this:
chardetect somefile.txt
somefile.txt: ascii with confidence 1.0
You can also use the library programmatically, check out the docs.
That’s it! 30 tips, tricks, and best practices to start off the new year. I hope you enjoyed
them as much as I enjoyed creating the list. If you have anything to add, feel free to
leave a comment!
medium.com
If you enjoyed this article, please subscribe to mySubstack.
12/12