20 useful Python tips and tricks you should know
Tags: python, beginners, programming, codenewbie
Published: 2019-10-22 08:41:06

---
canonical_url: https://www.blog.duomly.com/20-essential-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.

<h3>1. The Zen of Python</h3>
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:

```python
>>> 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!
```

<h3>2. Chained Assignment</h3>
If you need multiple variables to reference the same object, you can use the chained assignment:

```python
>>> x = y = z = 2
>>> x, y, z
(2, 2, 2)
```

Logical and elegant, right?

<h3>3. Chained Comparison</h3>
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:

```python
>>> x = 5
>>> 2 < x ≤ 8
True
>>> 6 < x ≤ 8
False
```

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:

```python
>>> 2 < x > 4
True
```

You can chain more than two comparisons:

```python
>>> x = 2
>>> y = 8
>>> 0 < x < 4 < y < 16
True
```

<h3>4. Multiple Assignment</h3>
You can assign multiple variables in a single statement using tuple unpacking:

```python
>>> x, y, z = 2, 4, 8
>>> x
2
>>> y
4
>>> z
8
```

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

<h3>5. More Advanced Multiple Assignment</h3>
Ordinary multiple assignments are not all Python can do. You don’t need the same number of elements on the left and right sides:

```python
>>> x, *y, z = 2, 4, 8, 16
>>> x
2
>>> y
[4, 8]
>>> z
16
```

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).

<h3>6. Swap Variables</h3>
You can apply multiple assignments to swap any two variables in a concise and elegant manner, without introducing the third one:

```python
>>> x, y = 2, 8
>>> x
2
>>> y
8
>>> x, y = y, x
>>> x
8
>>> y 2
```

<h3>7. Merge Dictionaries</h3>
One way to merge two or more dictionaries is by unpacking them in a new dict:

```python
>>> x = {'u': 1}
>>> y = {'v': 2}
>>> z = {**x, **y, 'w': 4}
>>> z
{'u': 1, 'v': 2, 'w': 4}
```

<h3>8. Join Strings</h3>
If you need to join multiple strings, eventually having the same character or group of characters between them, you can use str.join() method:

```python
>>> x = ['u', 'v', 'w']
>>> y = '-*-'.join(x)
>>> y
'u-*-v-*-w'
```

<h3>9. Advance Iteration</h3>
If you want to iterate through a sequence and you need both sequence elements and the corresponding indices, you should use enumerate:

```python
>>> 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
```

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

<h3>10. Reversed Iteration</h3>
If you want to iterate through a sequence in the reversed order, you should use reversed:

```python
>>> for item in reversed(['u', 'v', 'w']):
... print(item)
...
w
v
u
```

<h3>11. Aggregate Elements</h3>
If you’re going to aggregate the elements from several sequences, you should use zip:

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

>>> list(z)
[(1, 'u'), (2, 'v'), (4, 'w')]
```

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

<h3>12. Transpose Matrices</h3>
Although people usually apply NumPy (or similar libraries) when working with matrices, you can obtain the transpose of a matrix with zip:

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

<h3>13. Unique Values</h3>
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:

```python
>>> x = [1, 2, 1, 4, 8]
>>> y = set(x)
>>> y
{8, 1, 2, 4}
>>> z = list(y)
>>> z
[8, 1, 2, 4]
```

<h3>14. Sort Sequences</h3>
Sequences are sorted by their first elements by default:

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

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:

```python
>>> sorted([x, y, z], key=lambda item: item[1])
[(4, 'u'), (1, 'v'), (2, 'w')]
```

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

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

<h3>15. Sort Dictionaries</h3>
You can use a similar approach to sort key-value tuples of dictionaries obtained with .items() method:

```python
>>> x = {'u': 4, 'w': 2, 'v': 1}
>>> sorted(x.items())
[('u', 4), ('v', 1), ('w', 2)]
```

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:

```python
>>> 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)]
```

<h3>16. Raw Formatted Strings</h3>
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.

```python
>>> fr'u \ n v w={2 + 8}'
'u \\ n v w=10'
```

<h3>17. Obtain Current Date and Time</h3>
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:

```python
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2019, 5, 20, 1, 12, 31, 230217)
```

<h3>18. Obtain the Index of the Maximal (or Minimal) Element</h3>
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:

```python
>>> x = [2, 1, 4, 16, 8]
>>> max((item, i) for i, item in enumerate(x))[1]
3
```

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

```python
>>> y = [2, 1, 4, 8, 8]
>>> max((item, i) for i, item in enumerate(y))[1]
4
```

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

```python
>>> -max((item, -i) for i, item in enumerate(y))[1]
3
```

The alternative way is probably more elegant:

```python
>>> 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
```

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

<h3>19. Obtain the Cartesian Product</h3>
The built-in module itertools provides many potentially useful classes. One of them is a product used to obtain the Cartesian product:

```python
>>> 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)]
```

<h3>20. The Operator for Matrix Multiplication</h3>
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:

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

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

Happy coding!

<a href="https://www.duomly.com">
![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/7ptpsldw9ql2rzoo11mk.png)</a>