{"id":13411559,"url":"https://github.com/chiphuyen/python-is-cool","last_synced_at":"2025-04-04T11:14:39.121Z","repository":{"id":41811333,"uuid":"216587152","full_name":"chiphuyen/python-is-cool","owner":"chiphuyen","description":"Cool Python features for machine learning that I used to be too afraid to use. Will be updated as I have more time / learn more.","archived":false,"fork":false,"pushed_at":"2019-12-27T04:06:24.000Z","size":55,"stargazers_count":3578,"open_issues_count":3,"forks_count":563,"subscribers_count":118,"default_branch":"master","last_synced_at":"2025-03-28T10:09:23.721Z","etag":null,"topics":["advanced-python","data-science","machine-learning","python-tutorials","python3"],"latest_commit_sha":null,"homepage":"https://huyenchip.com","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chiphuyen.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-10-21T14:21:10.000Z","updated_at":"2025-03-27T15:50:14.000Z","dependencies_parsed_at":"2022-07-13T21:44:22.638Z","dependency_job_id":null,"html_url":"https://github.com/chiphuyen/python-is-cool","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chiphuyen%2Fpython-is-cool","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chiphuyen%2Fpython-is-cool/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chiphuyen%2Fpython-is-cool/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chiphuyen%2Fpython-is-cool/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chiphuyen","download_url":"https://codeload.github.com/chiphuyen/python-is-cool/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247166168,"owners_count":20894654,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["advanced-python","data-science","machine-learning","python-tutorials","python3"],"created_at":"2024-07-30T20:01:14.536Z","updated_at":"2025-04-04T11:14:39.093Z","avatar_url":"https://github.com/chiphuyen.png","language":"Jupyter Notebook","readme":"# python-is-cool\n\nA gentle guide to the Python features that I didn't know existed or was too afraid to use. This will be updated as I learn more and become less lazy.\n\nThis uses `python \u003e= 3.6`.\n\nGitHub has problem rendering Jupyter notebook so I copied the content here. I still keep the notebook in case you want to clone and run it on your machine, but you can also click the Binder badge below and run it in your browser.\n\n[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/chiphuyen/python-is-cool/master?urlpath=lab/tree/cool-python-tips.ipynb)\n\n## 1. Lambda, map, filter, reduce\nThe lambda keyword is used to create inline functions. The functions`square_fn` and `square_ld` below are identical.\n\n```python\ndef square_fn(x):\n    return x * x\n\nsquare_ld = lambda x: x * x\n\nfor i in range(10):\n    assert square_fn(i) == square_ld(i)\n```\n\nIts quick declaration makes `lambda` functions ideal for use in callbacks, and when functions are to be passed as arguments to other functions. They are especially useful when used in conjunction with functions like `map`, `filter`, and `reduce`.\n\n`map(fn, iterable)` applies the `fn` to all elements of the `iterable` (e.g. list, set, dictionary, tuple, string) and returns a map object.\n\n```python\nnums = [1/3, 333/7, 2323/2230, 40/34, 2/3]\nnums_squared = [num * num for num in nums]\nprint(nums_squared)\n\n==\u003e [0.1111111, 2263.04081632, 1.085147, 1.384083, 0.44444444]\n```\n\nThis is the same as calling using `map` with a callback function.\n\n```python\nnums_squared_1 = map(square_fn, nums)\nnums_squared_2 = map(lambda x: x * x, nums)\nprint(list(nums_squared_1))\n\n==\u003e [0.1111111, 2263.04081632, 1.085147, 1.384083, 0.44444444]\n```\n\nYou can also use `map` with more than one iterable. For example, if you want to calculate the mean squared error of a simple linear function `f(x) = ax + b` with the true label `labels`, these two methods are equivalent:\n\n```python\na, b = 3, -0.5\nxs = [2, 3, 4, 5]\nlabels = [6.4, 8.9, 10.9, 15.3]\n\n# Method 1: using a loop\nerrors = []\nfor i, x in enumerate(xs):\n    errors.append((a * x + b - labels[i]) ** 2)\nresult1 = sum(errors) ** 0.5 / len(xs)\n\n# Method 2: using map\ndiffs = map(lambda x, y: (a * x + b - y) ** 2, xs, labels)\nresult2 = sum(diffs) ** 0.5 / len(xs)\n\nprint(result1, result2)\n\n==\u003e 0.35089172119045514 0.35089172119045514\n```\n\nNote that objects returned by `map` and `filter` are iterators, which means that their values aren't stored but generated as needed. After you've called `sum(diffs)`, `diffs` becomes empty. If you want to keep all elements in `diffs`, convert it to a list using `list(diffs)`.\n\n`filter(fn, iterable)` works the same way as `map`, except that `fn` returns a boolean value and `filter` returns all the elements of the `iterable` for which the `fn` returns True.\n\n```python\nbad_preds = filter(lambda x: x \u003e 0.5, errors)\nprint(list(bad_preds))\n\n==\u003e [0.8100000000000006, 0.6400000000000011]\n```\n\n`reduce(fn, iterable, initializer)` is used when we want to iteratively apply an operator to all elements in a list. For example, if we want to calculate the product of all elements in a list:\n\n```python\nproduct = 1\nfor num in nums:\n    product *= num\nprint(product)\n\n==\u003e 12.95564683272412\n```\n\nThis is equivalent to:\n```python\nfrom functools import reduce\nproduct = reduce(lambda x, y: x * y, nums)\nprint(product)\n\n==\u003e 12.95564683272412\n```\n\n### Note on the performance of lambda functions\n\nLambda functions are meant for one time use. Each time `lambda x: dosomething(x)` is called, the function has to be created, which hurts the performance if you call `lambda x: dosomething(x)` multiple times (e.g. when you pass it inside `reduce`).\n\nWhen you assign a name to the lambda function as in `fn = lambda x: dosomething(x)`, its performance is slightly slower than the same function defined using `def`, but the difference is negligible. See [here](https://stackoverflow.com/questions/26540885/lambda-is-slower-than-function-call-in-python-why).\n\nEven though I find lambdas cool, I personally recommend using named functions when you can for the sake of clarity.\n\n## 2. List manipulation\nPython lists are super cool.\n\n### 2.1 Unpacking\nWe can unpack a list by each element like this:\n```python\nelems = [1, 2, 3, 4]\na, b, c, d = elems\nprint(a, b, c, d)\n\n==\u003e 1 2 3 4\n```\n\nWe can also unpack a list like this:\n\n```python\na, *new_elems, d = elems\nprint(a)\nprint(new_elems)\nprint(d)\n\n==\u003e 1\n    [2, 3]\n    4\n```\n\n### 2.2 Slicing\nWe know that we can reverse a list using `[::-1]`.\n\n```python\nelems = list(range(10))\nprint(elems)\n\n==\u003e [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nprint(elems[::-1])\n\n==\u003e [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n```\nThe syntax `[x:y:z]` means \\\"take every `z`th element of a list from index `x` to index `y`\\\". When `z` is negative, it indicates going backwards. When `x` isn't specified, it defaults to the first element of the list in the direction you are traversing the list. When `y` isn't specified, it defaults to the last element of the list. So if we want to take every 2th element of a list, we use `[::2]`.\n\n```python\nevens = elems[::2]\nprint(evens)\n\nreversed_evens = elems[-2::-2]\nprint(reversed_evens)\n\n==\u003e [0, 2, 4, 6, 8]\n    [8, 6, 4, 2, 0]\n```\n\nWe can also use slicing to delete all the even numbers in the list.\n\n```python\ndel elems[::2]\nprint(elems)\n\n==\u003e [1, 3, 5, 7, 9]\n```\n\n### 2.3 Insertion\nWe can change the value of an element in a list to another value.\n\n```python\nelems = list(range(10))\nelems[1] = 10\nprint(elems)\n\n==\u003e [0, 10, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\nIf we want to replace the element at an index with multiple elements, e.g. replace the value `1` with 3 values `20, 30, 40`:\n\n```python\nelems = list(range(10))\nelems[1:2] = [20, 30, 40]\nprint(elems)\n\n==\u003e [0, 20, 30, 40, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\nIf we want to insert 3 values `0.2, 0.3, 0.5` between element at index 0 and element at index 1:\n\n```python\nelems = list(range(10))\nelems[1:1] = [0.2, 0.3, 0.5]\nprint(elems)\n\n==\u003e [0, 0.2, 0.3, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\n### 2.4 Flattening\nWe can flatten a list of lists using `sum`.\n\n```python\nlist_of_lists = [[1], [2, 3], [4, 5, 6]]\nsum(list_of_lists, [])\n\n==\u003e [1, 2, 3, 4, 5, 6]\n```\n\nIf we have nested lists, we can recursively flatten it. That's another beauty of lambda functions -- we can use it in the same line as its creation.\n\n```python\nnested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]\nflatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]\nflatten(nested_lists)\n\n# This line of code is from\n# https://github.com/sahands/python-by-example/blob/master/python-by-example.rst#flattening-lists\n```\n\n### 2.5 List vs generator\nTo illustrate the difference between a list and a generator, let's look at an example of creating n-grams out of a list of tokens.\n\nOne way to create n-grams is to use a sliding window.\n\n```python\ntokens = ['i', 'want', 'to', 'go', 'to', 'school']\n\ndef ngrams(tokens, n):\n    length = len(tokens)\n    grams = []\n    for i in range(length - n + 1):\n        grams.append(tokens[i:i+n])\n    return grams\n\nprint(ngrams(tokens, 3))\n\n==\u003e [['i', 'want', 'to'],\n     ['want', 'to', 'go'],\n     ['to', 'go', 'to'],\n     ['go', 'to', 'school']]\n```\n\nIn the above example, we have to store all the n-grams at the same time. If the text has m tokens, then the memory requirement is `O(nm)`, which can be problematic when m is large.\n\nInstead of using a list to store all n-grams, we can use a generator that generates the next n-gram when it's asked for. This is known as lazy evaluation. We can make the function `ngrams` returns a generator using the keyword `yield`. Then the memory requirement is `O(m+n)`.\n\n```python\ndef ngrams(tokens, n):\n    length = len(tokens)\n    for i in range(length - n + 1):\n        yield tokens[i:i+n]\n\nngrams_generator = ngrams(tokens, 3)\nprint(ngrams_generator)\n\n==\u003e \u003cgenerator object ngrams at 0x1069b26d0\u003e\n\nfor ngram in ngrams_generator:\n    print(ngram)\n\n==\u003e ['i', 'want', 'to']\n    ['want', 'to', 'go']\n    ['to', 'go', 'to']\n    ['go', 'to', 'school']\n```\n\nAnother way to generate n-grams is to use slices to create lists: `[0, 1, ..., -n]`, `[1, 2, ..., -n+1]`, ..., `[n-1, n, ..., -1]`, and then `zip` them together.\n\n```python\ndef ngrams(tokens, n):\n    length = len(tokens)\n    slices = (tokens[i:length-n+i+1] for i in range(n))\n    return zip(*slices)\n\nngrams_generator = ngrams(tokens, 3)\nprint(ngrams_generator)\n\n==\u003e \u003czip object at 0x1069a7dc8\u003e # zip objects are generators\n\nfor ngram in ngrams_generator:\n    print(ngram)\n\n==\u003e ('i', 'want', 'to')\n    ('want', 'to', 'go')\n    ('to', 'go', 'to')\n    ('go', 'to', 'school')\n```\n\nNote that to create slices, we use `(tokens[...] for i in range(n))` instead of `[tokens[...] for i in range(n)]`. `[]` is the normal list comprehension that returns a list. `()` returns a generator.\n\n## 3. Classes and magic methods\nIn Python, magic methods are prefixed and suffixed with the double underscore `__`, also known as dunder. The most wellknown magic method is probably `__init__`.\n\n```python\nclass Node:\n    \"\"\" A struct to denote the node of a binary tree.\n    It contains a value and pointers to left and right children.\n    \"\"\"\n    def __init__(self, value, left=None, right=None):\n        self.value = value\n        self.left = left\n        self.right = right\n```\n\nWhen we try to print out a Node object, however, it's not very interpretable.\n\n```python\nroot = Node(5)\nprint(root) # \u003c__main__.Node object at 0x1069c4518\u003e\n```\n\nIdeally, when user prints out a node, we want to print out the node's value and the values of its children if it has children. To do so, we use the magic method `__repr__`, which must return a printable object, like string.\n\n```python\nclass Node:\n    \"\"\" A struct to denote the node of a binary tree.\n    It contains a value and pointers to left and right children.\n    \"\"\"\n    def __init__(self, value, left=None, right=None):\n        self.value = value\n        self.left = left\n        self.right = right\n\n    def __repr__(self):\n        strings = [f'value: {self.value}']\n        strings.append(f'left: {self.left.value}' if self.left else 'left: None')\n        strings.append(f'right: {self.right.value}' if self.right else 'right: None')\n        return ', '.join(strings)\n\nleft = Node(4)\nroot = Node(5, left)\nprint(root) # value: 5, left: 4, right: None\n```\n\nWe'd also like to compare two nodes by comparing their values. To do so, we overload the operator `==` with `__eq__`, `\u003c` with `__lt__`, and `\u003e=` with `__ge__`.\n\n```python\nclass Node:\n    \"\"\" A struct to denote the node of a binary tree.\n    It contains a value and pointers to left and right children.\n    \"\"\"\n    def __init__(self, value, left=None, right=None):\n        self.value = value\n        self.left = left\n        self.right = right\n\n    def __eq__(self, other):\n        return self.value == other.value\n\n    def __lt__(self, other):\n        return self.value \u003c other.value\n\n    def __ge__(self, other):\n        return self.value \u003e= other.value\n\n\nleft = Node(4)\nroot = Node(5, left)\nprint(left == root) # False\nprint(left \u003c root) # True\nprint(left \u003e= root) # False\n```\n\nFor a comprehensive list of supported magic methods [here](https://www.tutorialsteacher.com/python/magic-methods-in-python) or see the official Python documentation [here](https://docs.python.org/3/reference/datamodel.html#special-method-names) (slightly harder to read).\n\nSome of the methods that I highly recommend:\n\n- `__len__`: to overload the `len()` function.\n- `__str__`: to overload the `str()` function.\n- `__iter__`: if you want to your objects to be iterators. This also allows you to call `next()` on your object.\n\nFor classes like Node where we know for sure all the attributes they can support (in the case of Node, they are `value`, `left`, and `right`), we might want to use `__slots__` to denote those values for both performance boost and memory saving. For a comprehensive understanding of pros and cons of `__slots__`, see this [absolutely amazing answer by Aaron Hall on StackOverflow](https://stackoverflow.com/a/28059785/5029595).\n\n```python\nclass Node:\n    \"\"\" A struct to denote the node of a binary tree.\n    It contains a value and pointers to left and right children.\n    \"\"\"\n    __slots__ = ('value', 'left', 'right')\n    def __init__(self, value, left=None, right=None):\n        self.value = value\n        self.left = left\n        self.right = right\n```\n## 4. local namespace, object's attributes\nThe `locals()` function returns a dictionary containing the variables defined in the local namespace.\n\n```python\nclass Model1:\n    def __init__(self, hidden_size=100, num_layers=3, learning_rate=3e-4):\n        print(locals())\n        self.hidden_size = hidden_size\n        self.num_layers = num_layers\n        self.learning_rate = learning_rate\n\nmodel1 = Model1()\n\n==\u003e {'learning_rate': 0.0003, 'num_layers': 3, 'hidden_size': 100, 'self': \u003c__main__.Model1 object at 0x1069b1470\u003e}\n```\n\nAll attributes of an object are stored in its `__dict__`.\n```python\nprint(model1.__dict__)\n\n==\u003e {'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}\n```\n\nNote that manually assigning each of the arguments to an attribute can be quite tiring when the list of the arguments is large. To avoid this, we can directly assign the list of arguments to the object's `__dict__`.\n\n```python\nclass Model2:\n    def __init__(self, hidden_size=100, num_layers=3, learning_rate=3e-4):\n        params = locals()\n        del params['self']\n        self.__dict__ = params\n\nmodel2 = Model2()\nprint(model2.__dict__)\n\n==\u003e {'learning_rate': 0.0003, 'num_layers': 3, 'hidden_size': 100}\n```\n\nThis can be especially convenient when the object is initiated using the catch-all `**kwargs`, though the use of `**kwargs` should be reduced to the minimum.\n\n```python\nclass Model3:\n    def __init__(self, **kwargs):\n        self.__dict__ = kwargs\n\nmodel3 = Model3(hidden_size=100, num_layers=3, learning_rate=3e-4)\nprint(model3.__dict__)\n\n==\u003e {'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}\n```\n\n## 5. Wild import\nOften, you run into this wild import `*` that looks something like this:\n\n`file.py`\n```python\n    from parts import *\n```\n\nThis is irresponsible because it will import everything in module, even the imports of that module. For example, if `parts.py` looks like this:\n\n`parts.py`\n```python\nimport numpy\nimport tensorflow\n\nclass Encoder:\n    ...\n\nclass Decoder:\n    ...\n\nclass Loss:\n    ...\n\ndef helper(*args, **kwargs):\n    ...\n\ndef utils(*args, **kwargs):\n    ...\n```\n\nSince `parts.py` doesn't have `__all__` specified, `file.py` will import Encoder, Decoder, Loss, utils, helper together with numpy and tensorflow.\n\nIf we intend that only Encoder, Decoder, and Loss are ever to be imported and used in another module, we should specify that in `parts.py` using the `__all__` keyword.\n\n`parts.py`\n```python\n __all__ = ['Encoder', 'Decoder', 'Loss']\nimport numpy\nimport tensorflow\n\nclass Encoder:\n    ...\n```\nNow, if some user irresponsibly does a wild import with `parts`, they can only import Encoder, Decoder, Loss. Personally, I also find `__all__` helpful as it gives me an overview of the module.\n\n## 6. Decorator to time your functions\nIt's often useful to know how long it takes a function to run, e.g. when you need to compare the performance of two algorithms that do the same thing. One naive way is to call `time.time()` at the begin and end of each function and print out the difference.\n\nFor example: compare two algorithms to calculate the n-th Fibonacci number, one uses memoization and one doesn't.\n\n```python\ndef fib_helper(n):\n    if n \u003c 2:\n        return n\n    return fib_helper(n - 1) + fib_helper(n - 2)\n\ndef fib(n):\n    \"\"\" fib is a wrapper function so that later we can change its behavior\n    at the top level without affecting the behavior at every recursion step.\n    \"\"\"\n    return fib_helper(n)\n\ndef fib_m_helper(n, computed):\n    if n in computed:\n        return computed[n]\n    computed[n] = fib_m_helper(n - 1, computed) + fib_m_helper(n - 2, computed)\n    return computed[n]\n\ndef fib_m(n):\n    return fib_m_helper(n, {0: 0, 1: 1})\n```\n\nLet's make sure that `fib` and `fib_m` are functionally equivalent.\n\n```python\nfor n in range(20):\n    assert fib(n) == fib_m(n)\n```\n\n```python\nimport time\n\nstart = time.time()\nfib(30)\nprint(f'Without memoization, it takes {time.time() - start:7f} seconds.')\n\n==\u003e Without memoization, it takes 0.267569 seconds.\n\nstart = time.time()\nfib_m(30)\nprint(f'With memoization, it takes {time.time() - start:.7f} seconds.')\n\n==\u003e With memoization, it takes 0.0000713 seconds.\n```\n\nIf you want to time multiple functions, it can be a drag having to write the same code over and over again. It'd be nice to have a way to specify how to change any function in the same way. In this case would be to call time.time() at the beginning and the end of each function, and print out the time difference.\n\nThis is exactly what decorators do. They allow programmers to change the behavior of a function or class. Here's an example to create a decorator `timeit`.\n\n```python\ndef timeit(fn): \n    # *args and **kwargs are to support positional and named arguments of fn\n    def get_time(*args, **kwargs): \n        start = time.time() \n        output = fn(*args, **kwargs)\n        print(f\"Time taken in {fn.__name__}: {time.time() - start:.7f}\")\n        return output  # make sure that the decorator returns the output of fn\n    return get_time \n```\n\nAdd the decorator `@timeit` to your functions.\n\n```python\n@timeit\ndef fib(n):\n    return fib_helper(n)\n\n@timeit\ndef fib_m(n):\n    return fib_m_helper(n, {0: 0, 1: 1})\n\nfib(30)\nfib_m(30)\n\n==\u003e Time taken in fib: 0.2787242\n==\u003e Time taken in fib_m: 0.0000138\n```\n\n## 7. Caching with @functools.lru_cache\nMemoization is a form of cache: we cache the previously calculated Fibonacci numbers so that we don't have to calculate them again.\n\nCaching is such an important technique that Python provides a built-in decorator to give your function the caching capacity. If you want `fib_helper` to reuse the previously calculated Fibonacci numbers, you can just add the decorator `lru_cache` from `functools`. `lru` stands for \"least recently used\". For more information on cache, see [here](https://docs.python.org/3/library/functools.html).\n\n```python\nimport functools\n\n@functools.lru_cache()\ndef fib_helper(n):\n    if n \u003c 2:\n        return n\n    return fib_helper(n - 1) + fib_helper(n - 2)\n\n@timeit\ndef fib(n):\n    \"\"\" fib is a wrapper function so that later we can change its behavior\n    at the top level without affecting the behavior at every recursion step.\n    \"\"\"\n    return fib_helper(n)\n\nfib(50)\nfib_m(50)\n\n==\u003e Time taken in fib: 0.0000412\n==\u003e Time taken in fib_m: 0.0000281\n```\n","funding_links":[],"categories":["Jupyter Notebook","Please find below the links to awesome cheat-sheet and resources:"],"sub_categories":["Python:"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchiphuyen%2Fpython-is-cool","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchiphuyen%2Fpython-is-cool","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchiphuyen%2Fpython-is-cool/lists"}