Pythonian code
General
-
Conditional or Ternary operator
-
lambda function
-
Single line functions in python are lambda functions
-
Ignore output by using an underscore
-
splat operator: allows lists and dictionaries to be unpacked1
-
walrus operator:
List
-
list comprehension
-
multiple level list comprehension
-
list comprehension + if statement
-
list comprehension + if/else statement
-
finding and removing an element from list
-
filtering elements in a list based on a condition
-
swapping elements in a list
Dict
-
dict comprehension
-
iterating through dict keys or/and values
-
getting values from dictionary
Common modules
Argparse
Easy to setup command line input.
Itertools
Generating combinations in python.
Use case: Get all possible combinations of each of the lists in this list of lists2 - [[1,2], [2,3], [4,5,6], [1]]
Logging
I like to copy the logs to stderr3 when a verbose flag is passed, so that I can directly read the command line output and don’t have to look at the log.
os and glob
-
Finding specific files in a folder:
Pickle
Note: If you have to pickle lambda functions or functions returning another function, use dill instead of pickle (drop in replacement).4
Regular expressions
IPython (Jupyter)
-
Autoreload libraries5
-
timeit - very useful to calculate how fast your function/code is
-
Clear variables
-
Progress bar
Footnotes
-
https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists and https://stackoverflow.com/questions/4979542/python-use-list-as-function-parameters ↩
-
https://stackoverflow.com/questions/3169825/generating-combinations-in-python and https://docs.python.org/3/library/itertools.html#itertools.product ↩
-
https://stackoverflow.com/questions/25348532/can-python-pickle-lambda-functions ↩
-
https://stackoverflow.com/questions/56059651/how-to-make-vscode-auto-reload-external-py-modules#57245926 ↩