Cool Python tricks you are not using, but you should.
Cool Python tricks you are not using, but you should.
Ternary operator
=
is same as
=
=
Short circuit
= or 15
is same as
=
is same as
= 15
=
Comparison
instead of
Reverse an iterable
# => [4, 3, 2, 1]
Unpacking
=
* , =
,
is same as
=
=
=
swapping two variables
= ,
, # 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
>>> =
>>>
>>> * , =
# if you do not want to use the non-last elements
>>>
>>> =
>>>
For set
>>> =
>>>
: is not
>>> , , =
>>>
>>> * , =
>>>
>>>
# 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.
-l
: I use 120 as the maximum characters I accept in a line-t py38
: Python 3.8 specific custom formatting.