DEV Community

Cover image for 20 useful Python tips and tricks you should know
Duomly
Duomly

Posted on • Updated on • Originally published at blog.duomly.com

20 useful Python tips and tricks you should know

This article was originally published at: https://www.blog.duomly.com/20-essential-python-tips-and-tricks-you-should-know/

Python is a popular, general-purpose, and widely used programming language. It’s used for data science and machine learning, scientific computing in many areas, back-end Web development, mobile and desktop applications, and so on. Many well-known companies use Python: Google, Dropbox, Facebook, Mozilla, IBM, Quora, Amazon, Spotify, NASA, Netflix, Reddit, and many more.

Python is free and open-source, as well as most of the products related to it. Also, it has a large, dedicated, and friendly community of programmers and other users.

Its syntax is designed with simplicity, readability, and elegance in mind.

This article presents 20 Python tips and tricks that might be useful.

1. The Zen of Python

The Zen of Python also known as PEP 20 is a small text by Tim Peters that represents the guiding principles to design and use Python. It can be found on Python Web site, but you can also get it in your terminal (console) or Jupyter notebook with a single statement:

>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Enter fullscreen mode Exit fullscreen mode

2. Chained Assignment

If you need multiple variables to reference the same object, you can use the chained assignment:

>>> x = y = z = 2
>>> x, y, z
(2, 2, 2)
Enter fullscreen mode Exit fullscreen mode

Logical and elegant, right?

3. Chained Comparison

You can merge multiple comparisons to a single Python expression by chaining the comparison operators. This expression returns True if all comparisons are correct or False otherwise:

>>> x = 5
>>> 2 < x  8
True
>>> 6 < x  8
False
Enter fullscreen mode Exit fullscreen mode

This is similar to (2 < x) and (x ≤ 8) and (6 < x) and (x ≤ 8), but more compact and requires x to be evaluated only once.

This is also legal:

>>> 2 < x > 4
True
Enter fullscreen mode Exit fullscreen mode

You can chain more than two comparisons:

>>> x = 2
>>> y = 8
>>> 0 < x < 4 < y < 16
True
Enter fullscreen mode Exit fullscreen mode

4. Multiple Assignment

You can assign multiple variables in a single statement using tuple unpacking:

>>> x, y, z = 2, 4, 8
>>> x
2
>>> y
4
>>> z
8
Enter fullscreen mode Exit fullscreen mode

Please, note that 2, 4, 8 in the first statement is a tuple equivalent to (2, 4, 8).

5. More Advanced Multiple Assignment

Ordinary multiple assignments are not all Python can do. You don’t need the same number of elements on the left and right sides:

>>> x, *y, z = 2, 4, 8, 16
>>> x
2
>>> y
[4, 8]
>>> z
16
Enter fullscreen mode Exit fullscreen mode

In this case, x takes the first value (2) because it comes first. z is the last and takes the last value (8). y takes all other values packed in a list because it has the asterisk (*y).

6. Swap Variables

You can apply multiple assignments to swap any two variables in a concise and elegant manner, without introducing the third one:

>>> x, y = 2, 8
>>> x
2
>>> y
8
>>> x, y = y, x
>>> x
8
>>> y 2
Enter fullscreen mode Exit fullscreen mode

7. Merge Dictionaries

One way to merge two or more dictionaries is by unpacking them in a new dict:

>>> x = {'u': 1}
>>> y = {'v': 2}
>>> z = {**x, **y, 'w': 4}
>>> z
{'u': 1, 'v': 2, 'w': 4}
Enter fullscreen mode Exit fullscreen mode

8. Join Strings

If you need to join multiple strings, eventually having the same character or group of characters between them, you can use str.join() method:

>>> x = ['u', 'v', 'w']
>>> y = '-*-'.join(x)
>>> y
'u-*-v-*-w'
Enter fullscreen mode Exit fullscreen mode

9. Advance Iteration

If you want to iterate through a sequence and you need both sequence elements and the corresponding indices, you should use enumerate:

>>> for i, item in enumerate(['u', 'v', 'w']):
... print('index:', i, 'element:', item)
...
index: 0 element: u
index: 1 element: v
index: 2 element: w
Enter fullscreen mode Exit fullscreen mode

In each iteration, you’ll get a tuple with the index and corresponding element of the sequence.

10. Reversed Iteration

If you want to iterate through a sequence in the reversed order, you should use reversed:

>>> for item in reversed(['u', 'v', 'w']):
... print(item)
...
w
v
u
Enter fullscreen mode Exit fullscreen mode

11. Aggregate Elements

If you’re going to aggregate the elements from several sequences, you should use zip:

>>> x = [1, 2, 4]
>>> y = ('u', 'v', 'w')
>>> z = zip(x, y)
>>> z

>>> list(z)
[(1, 'u'), (2, 'v'), (4, 'w')]
Enter fullscreen mode Exit fullscreen mode

You can iterate through the obtained zip object or transform it into a list or tuple.

12. Transpose Matrices

Although people usually apply NumPy (or similar libraries) when working with matrices, you can obtain the transpose of a matrix with zip:

>>> x = [(1, 2, 4), ('u', 'v', 'w')]
>>> y = zip(*x)
>>> z = list(y)
>>> z
[(1, 'u'), (2, 'v'), (4, 'w')]
Enter fullscreen mode Exit fullscreen mode

13. Unique Values

You can remove duplicates from a list, that is obtained unique values by converting it to a set if the order of elements is not important:

>>> x = [1, 2, 1, 4, 8]
>>> y = set(x)
>>> y
{8, 1, 2, 4}
>>> z = list(y)
>>> z
[8, 1, 2, 4]
Enter fullscreen mode Exit fullscreen mode

14. Sort Sequences

Sequences are sorted by their first elements by default:

>>> x = (1, 'v')
>>> y = (4, 'u')
>>> z = (2, 'w')
>>> sorted([x, y, z])
[(1, 'v'), (2, 'w'), (4, 'u')]
Enter fullscreen mode Exit fullscreen mode

However, if you want to sort them according to their second (or other) elements, you can use the parameter key and an appropriate lambda function as the corresponding argument:

>>> sorted([x, y, z], key=lambda item: item[1])
[(4, 'u'), (1, 'v'), (2, 'w')]
Enter fullscreen mode Exit fullscreen mode

It’s similar if you want to obtain the reversed order:

>>> sorted([x, y, z], key=lambda item: item[1], reverse=True)
[(2, 'w'), (1, 'v'), (4, 'u')]
Enter fullscreen mode Exit fullscreen mode

15. Sort Dictionaries

You can use a similar approach to sort key-value tuples of dictionaries obtained with .items() method:

>>> x = {'u': 4, 'w': 2, 'v': 1}
>>> sorted(x.items())
[('u', 4), ('v', 1), ('w', 2)]
Enter fullscreen mode Exit fullscreen mode

They are sorted according to the keys. If you want to them to be sorted according to their values, you should specify the arguments that correspond to key and eventually reverse:

>>> sorted(x.items(), key=lambda item: item[1])
[('v', 1), ('w', 2), ('u', 4)]
>>> sorted(x.items(), key=lambda item: item[1], reverse=True)
[('u', 4), ('w', 2), ('v', 1)]
Enter fullscreen mode Exit fullscreen mode

16. Raw Formatted Strings

PEP 498 and Python 3.6 introduced so-called formatted strings or f-strings. You can embed expressions inside such strings. It’s possible and straightforward to treat a string as both raw and formatted. You need to include both prefixes: fr.

>>> fr'u \ n v w={2 + 8}'
'u \\ n v w=10'
Enter fullscreen mode Exit fullscreen mode

17. Obtain Current Date and Time

Python has a built-in module datetime that is versatile in working with dates and times. One of its methods, .now(), returns the current date and time:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2019, 5, 20, 1, 12, 31, 230217)
Enter fullscreen mode Exit fullscreen mode

18. Obtain the Index of the Maximal (or Minimal) Element

Python doesn’t provide a routine to directly get the index of the maximal or minimal element in a list or tuple. Fortunately, there are (at least) two elegant ways to do so:

>>> x = [2, 1, 4, 16, 8]
>>> max((item, i) for i, item in enumerate(x))[1]
3
Enter fullscreen mode Exit fullscreen mode

If there are two or more elements with the maximal value, this approach returns the index of the last one:

>>> y = [2, 1, 4, 8, 8]
>>> max((item, i) for i, item in enumerate(y))[1]
4
Enter fullscreen mode Exit fullscreen mode

To get the index of the first occurrence, you need to change the previous statement slightly:

>>> -max((item, -i) for i, item in enumerate(y))[1]
3
Enter fullscreen mode Exit fullscreen mode

The alternative way is probably more elegant:

>>> x = [2, 1, 4, 16, 8]
>>> max(range(len(x)), key=lambda i: x[i])
3
>>> y = [2, 1, 4, 8, 8]
>>> max(range(len(y)), key=lambda i: x[i])
3
Enter fullscreen mode Exit fullscreen mode

To find the index of the minimal element, use the function min instead of max.

19. Obtain the Cartesian Product

The built-in module itertools provides many potentially useful classes. One of them is a product used to obtain the Cartesian product:

>>> import itertools
>>> x, y, z = (2, 8), ['u', 'v', 'w'], {True, False}
>>> list(itertools.product(x, y, z))
[(2, 'u', False), (2, 'u', True), (2, 'v', False), (2, 'v', True),
(2, 'w', False), (2, 'w', True), (8, 'u', False), (8, 'u', True),
(8, 'v', False), (8, 'v', True), (8, 'w', False), (8, 'w', True)]
Enter fullscreen mode Exit fullscreen mode

20. The Operator for Matrix Multiplication

PEP 465 and Python 3.5 introduced the dedicated infix operator for matrix multiplication @. You can implement it for your class with the methods matmul, rmatmul, and imatmul. This is how elegant the code for multiplying vectors or matrices looks like:

>>> import numpy as np
>>> x, y = np.array([1, 3, 5]), np.array([2, 4, 6])
>>> z = x @ y
>>> z
44
Enter fullscreen mode Exit fullscreen mode

Conclusion

You’ve seen 20 Python tips and tricks that make it interesting and elegant. There are many other language features worth exploring.

Happy coding!


Duomly - Programming Online Courses

Top comments (3)

Collapse
 
thefern profile image
Fernando B 🚀

I'll add a few more to the awesome list!

Comprehension list, I actually like for loops written in full but if you want to save space here and there comp. lists can help with that:

[ expression for item in list if conditional ]

for item in list:
    if conditional:
        expression

I like to run pep8 linter sometimes on cmd line, of course you can have a linter on your text editor too, below is the way to do it from cmd line:

github.com/PyCQA/pycodestyle

pip install pycodestyle

$ pycodestyle --first optparse.py
optparse.py:69:11: E401 multiple imports on one line
optparse.py:77:1: E302 expected 2 blank lines, found 1
optparse.py:88:5: E301 expected 1 blank line, found 0
optparse.py:222:34: W602 deprecated form of raising exception
optparse.py:347:31: E211 whitespace before '('
optparse.py:357:17: E201 whitespace after '{'
optparse.py:472:29: E221 multiple spaces before operator
optparse.py:544:21: W601 .has_key() is deprecated, use 'in'
Collapse
 
aurelmegn profile image
Aurel

Also, it would be great to mention all, and any functions to evaluate lists