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:

>>> a, *b, c = 1, 2, 3, 4, 5, 6
>>> a
1
>>> b
[2, 3, 4, 5]
>>> c
6

What did just happen? When we use the * operator in this context, it will extend the unpacking functionality to allow us to collect or pack multiple values in a single variable. Exactly all the once which were not used by the expression. It’s awesome, just remember you can have only one * operator in the assignment to avoid SyntaxError.

>>> a, *b, c, *d = 1, 2, 3, 4, 5, 6
  File "<stdin>", line 1
SyntaxError: two starred expressions in assignment

but you can also unpack lists:

>>> a, b, c = ['a', 'b', 'c']
>>> a
'a'

or strings….

>>> a, b, c = 'def'
>>> a
'd'

actually, you can use any iterable in this way. But let me show you one more cool thing before we jump to the next topic:

>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1

Isn’t that the most beautiful variable swap ever?


Checking against None

The None keyword in Python is used to define a null value, or no value at all. Unlike other languages, None in Python is a datatype of its own (NoneType) and only None can be None. Let’s see it in examples how does it work:

x = None

>>> type(x)
<class 'NoneType'>

>>> x == 0
False

>>> x == False
False

If you want to check if a variable is actually None you could do something like this:

>>> x == None
True

And it is valid, however there’s a more Pythonic way of doing it:

>>> x is None
True

>>> x is not None
False

It does the same job, however, it looks more human.

#python #python style #make your code great

Make Your Code Great, Python Style
1.40 GEEK