Python is a great programming language that offers us amazing tools to make our code more readable, concise, and cool. Today I’d like to talk about ways to write more Pythonic code, we will cover some great tricks that will improve the quality of your code. Let’s start…

Using Unpacking

Python allows a tuple (or list) of variables to appear on the assignment side of an operation. This allows us to simplify our code, making it more readable.

Let’s start with an example of unpacking tuples:

>>> a, b, c = (1, 2, 3)
>>> a
1
>>> b
2
>>> c
3

Easy enough, more than one variable can be on the left side of our assignment operation, while the values on the right side are assigned one by one to each of the variables. Just be aware that the number of items on the left side should equal the number of items on the right, or you may get a ValueError like this:

>>> a, b = 1, 2, 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> a, b, c = 1, 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)

However, since Python is awesome, there are ways to prevent this from happening, you can do something like:

#python

Learn Some Tricks to Write Better Python code
18.45 GEEK