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

Subscribe to my newsletter and never miss my upcoming articles

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.

Further reading

 
Share this