Cool Python tricks you are not using, but you should.

Cool Python tricks you are not using, but you should.

Cool Python tips and tricks

Soumendra kumar sahoo
·Aug 22, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Ternary operator
  • Short circuit
  • Comparison
  • Reverse an iterable
  • Unpacking
  • Code formatting
  • Further reading

Ternary operator

ans = z if a > b else c

is same as

if a > b:
    ans = z
else:
    ans = c

Short circuit

result = counter or 15

is same as

result = counter if counter else 15

is same as

if not counter:
    result = 15
else:
    result = counter

Comparison

if 3 > a > 1 < b < 5: foo()

instead of

if a > 1 and b > 1 and  a < 3 and  b < 5: foo()

Reverse an iterable

[1, 2, 3, 4][::-1] # => [4, 3, 2, 1]

Unpacking

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

is same as

b = []
for i, val in enumerate(z):
    if i == 0:
        a = val
    elif i == len(z) - 1:
        c = val
    else:
        b.append(val)

swapping two variables

a, b = b, a
# this is tuple unpacking

Last element of an iterable

To fetch the last element of any iterable like list, tuple or set.

For list/tuple

>>> zlst = ['a', 'b', 'c']
>>> zlst[-1]
'c'
>>> *_, e = zlst
# if you do not want to use the non-last elements
>>> e
'c'
>>> ztup = ('a', 'b', 'c')
>>> ztup[-1]
'c'

For set

>>> my_set = {'a', 'b', 'c'}
>>> my_set[-1]
TypeError: 'set' object is not subscriptable
>>> q, w, e = my_set
>>> e
'c'
>>> *q, e = my_set
>>> e
'c'
>>> q
['a', 'b']
# q is not a set

More tricks will be added soon. The cover picture is copyrighted to the author.

Code formatting

  • Use black to format your codebase.
  • Have a large project, can do one at a time or one file at a time.
  • Here is my favorite config I use to auto-format my code modules.
$ pip install black
$ black folder/file.py -l 120 -t py38 
reformatted folder/file.py
All done! ✨ 🍰 ✨
1 file reformatted.
  • -l: I use 120 as the maximum characters I accept in a line
  • -t py38: Python 3.8 specific custom formatting.

Further reading

Did you find this article valuable?

Support Soumendra kumar sahoo by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this

Impressum

Views are my own and not represent of my employer.
All articles and images are CC-BY-SA-4.0 licensed unless or until explicitly specified.