{"id":13459649,"url":"https://github.com/lifeparticle/Python-Cheatsheet","last_synced_at":"2025-03-24T18:31:02.924Z","repository":{"id":78268769,"uuid":"239196157","full_name":"lifeparticle/Python-Cheatsheet","owner":"lifeparticle","description":"The missing Cheatsheet for Python","archived":false,"fork":false,"pushed_at":"2022-12-04T04:20:59.000Z","size":1689,"stargazers_count":20,"open_issues_count":1,"forks_count":8,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-05-21T14:05:57.583Z","etag":null,"topics":["awesome","basic","cheatsheet","docker","programming","python"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lifeparticle.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2020-02-08T19:58:08.000Z","updated_at":"2023-11-27T13:10:09.000Z","dependencies_parsed_at":"2023-03-05T10:30:25.534Z","dependency_job_id":null,"html_url":"https://github.com/lifeparticle/Python-Cheatsheet","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/lifeparticle%2FPython-Cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FPython-Cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FPython-Cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FPython-Cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lifeparticle","download_url":"https://codeload.github.com/lifeparticle/Python-Cheatsheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221995733,"owners_count":16913552,"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":["awesome","basic","cheatsheet","docker","programming","python"],"created_at":"2024-07-31T10:00:23.920Z","updated_at":"2024-10-29T05:31:10.876Z","avatar_url":"https://github.com/lifeparticle.png","language":"Jupyter Notebook","readme":"[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/lifeparticle/Python-Cheatsheet/issues)\n\nTable of Contents\n=================\n\n   * [Installation](#installation)\n      * [How to install python](#how-to-install-python)\n   * [Comment](#comment)\n   * [Operators](#operators)\n      * [Logical operators](#logical-operators)\n      * [Bitwise operators](#bitwise-operators)\n      * [Arithmetic operators](#arithmetic-operators)\n      * [Comparison operators](#comparison-operators)\n      * [Assignment operators](#assignment-operators)\n   * [Conditional structures](#conditional-structures)\n      * [Ternary Operators](#ternary-operators)\n   * [Data types](#data-types)\n      * [How to check data type](#how-to-check-data-type)\n      * [String](#string)\n      * [List](#list)\n      * [Dictionary](#dictionary)\n      * [Set](#set)\n   * [map() Function](#map-function)\n   * [filter() Function](#filter-function)\n   * [reduce() Function](#reduce-function)\n   * [zip() Function](#zip-function)\n   * [format() function](#format-function)\n   * [Miscellaneous](#miscellaneous)\n      * [Get the number of bits in an integer in binary, excluding the sign and leading zeros.](#get-the-number-of-bits-in-an-integer-in-binary-excluding-the-sign-and-leading-zeros)\n      * [Swap two variables in one line](#swap-two-variables-in-one-line)\n   * [Books and other resources](#books-and-other-resources)\n   * [Bug Reports and Feature Requests](#bug-reports-and-feature-requests)\n   * [Author](#author)\n   * [License](#license)\n\nInstallation\n============\n\nHow to install python\n-----\nIf you don't want to install python natively you can use [docker](https://www.docker.com/).\n```\ndocker run -it --rm python:latest\n# check which version of python you're running\npython --version\n```\n\n\nComment\n============\n\n```python\n# single line comment\n\n# begin\n# multiline\n# comment\n# end\n```\n\nor\n```python\n\"\"\"\nbegin\nmultiline\ncomment\nend\n\"\"\"\n```\n\nOperators\n============\nLogical operators\n-----\n| No | operator |\n|---|---|\n| 1 | and   |\n| 2 | or    |\n| 3 | not   |\n| 4 | \u0026\u0026    |\n| 5 | \\|\\|  |\n| 6 | !     |\n\n\nBitwise operators\n-----\n| No | operator |\n|---|---|\n| 1 | \u0026     |\n| 2 | \\|    |\n| 3 | ^     |\n| 4 | ~     |\n| 5 | \u003c\u003c    |\n| 6 | \u003e\u003e    |\n\nArithmetic operators\n-----\n| No | operator |\n|---|---|\n| 1 | +     |\n| 2 | -     |\n| 3 | *     |\n| 4 | /     |\n| 5 | %     |\n| 6 | **    |\n| 7 | //    |\n\nComparison operators\n-----\n| No | operator |\n|---|---|\n| 1  | ==     |\n| 2  | !=     |\n| 3  | \u003e      |\n| 4  | \u003c      |\n| 5  | \u003e=     |\n| 6  | \u003c=     |\n| 7  | \u003c\u003e     |\n\n\nAssignment operators\n-----\n| No | operator |\n|---|---|\n| 1 | =     |\n| 2 | +=    |\n| 3 | -=    |\n| 4 | *=    |\n| 5 | /=    |\n| 6 | %=    |\n| 7 | **=   |\n| 8 | //=   |\n\n\nConditional structures\n============\n\n```python\nx = 11\nif x \u003e 10:\n    print(\"The number is greater than 10\")\nelse:\n    print(\"The number is not greater than 10\")\n```\n\n```python\nif x == 10:\n    print('The value of x is 10')\nelif x == 11:\n    print('The value of x is 11')\nelse:\n    print('The value of x is not either 10 or 11')\n```\n\nTernary Operators\n-----\n```\nexecute_if_true if condition else execute_if_false\n```\n\n```python\nprint \"even\" if 6 % 2 == 0 else \"odd\"\n\n# output\n# even\n```\n\nData types\n============\n\n| No | Type  | Example  | Class  | Type  |\n|---|---|---|---|---|\n| 1  | int        | \u003e a = 17                           |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'int'        | Numeric Types         |\n| 2  | float      | \u003e a = 87.23                        |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'float'      | Numeric Types         |\n| 3  | complex    | \u003e a = 1j or \u003e a = 1J               |\u003e `a.__class__.__name__`` \u003cbr\u003e \u003e 'complex'    | Numeric Types         |\n| 4  | str        | \u003e a = \"Hello universe\"             |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'str'        | Text Sequence Type    |\n| 5  | list       | \u003e a = [\"a\", \"b\", \"c\"]              |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'list'       | Sequence Types        |\n| 6  | tuple      | \u003e a = (\"a\", \"b\", \"c\")              |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'tuple'      | Sequence Types        |\n| 7  | range      | \u003e a = range(7)                     |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'range'      | Sequence Types        |\n| 8  | dict       | \u003e a = {\"name\" : \"Tom\", \"age\" : 17} |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'dict'       | Mapping Types         |\n| 9  | set        | \u003e a = {\"a\", \"b\", \"c\"}              |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'set'        | Set Types             |\n| 10 | frozenset  | \u003e a = frozenset({\"a\", \"b\", \"c\"})   |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'frozenset'  | Set Types             |\n| 11 | bool       | \u003e a = True                         |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'bool'       | Boolean Types         |\n| 12 | bytes      | \u003e a = b\"Hello universe\"            |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'bytes'      | Binary Sequence Types |\n| 13 | bytearray  | \u003e a = bytearray(7)                 |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'bytearray'  | Binary Sequence Types |\n| 14 | memoryview | \u003e a = memoryview(bytes(7))         |\u003e `a.__class__.__name__` \u003cbr\u003e \u003e 'memoryview' | Binary Sequence Types |\n\n\n[Further readings](https://docs.python.org/3/library/stdtypes.html)\n\n\nHow to check data type\n-----\n\n```python\na = 37\nisinstance(a, int)\n# True\nisinstance(a, float)\n# False\n```\n\n```python\ntype(10)\n# \u003ctype 'int'\u003e\n```\n\nString\n-----\n\n```python\nprint('Hello World'[0])\n# H\nprint('Hello World'[1])\n# e\n```\n\n\nList\n-----\n\n```python\na = [\"a\", \"b\", \"c\"]\n\nf, s, t = [\"a\", \"b\", \"c\"]\n# output\n# f = 'a'\n# s = 'b'\n# t = 'c'\n\nf, *mid, l = [\"a\", \"b\", \"c\"]\n\n# output\n# f = 'a'\n# mid = ['b']\n# l = 'c'\n```\n\n```python\na = [\"a\", \"b\", \"c\"]\nb = [\"d\", \"e\", \"f\"]\n\na.append(b)\n# output\n# ['a', 'b', 'c', ['d', 'e', 'f']]\n\na = [\"a\", \"b\", \"c\"]\nb = [\"d\", \"e\", \"f\"]\n\na.extend(b)\n# output\n# ['a', 'b', 'c', 'd', 'e', 'f']\n```\n\nList slice\n\nlist[start_index:stop_index:step]\n\n```python\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nnumbers[0::2]\n\n# output\n# [1, 3, 5, 7, 9]\n\n\nnumbers[1::2]\n\n# output\n# [2, 4, 6, 8, 10]\n```\n\nList Comprehensions\n\nCreate a list of lists\n\n```python\n[[0]*2 for i in range(2)]\n\n# output\n# [[0, 0], [0, 0]]\n```\n\nCreate a list of variable length of lists\n\n```python\nn = 10\n[[0]*(i+1) for i in range(n)] + [[0]*i for i in range(n-1, 0, -1)]\n\n# output\n# [[0],\n# [0, 0],\n# [0, 0, 0],\n# [0, 0, 0, 0],\n# [0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0],\n# [0, 0, 0, 0],\n# [0, 0, 0],\n# [0, 0],\n# [0]]\n```\n\nCreate a matrix of multiplication tables\n\n```python\nn = 5\n[[i*j for i in range(1,n+1)] for j in range(1, n+1)]\n\n# output\n# [[1, 2, 3, 4, 5],\n# [2, 4, 6, 8, 10],\n# [3, 6, 9, 12, 15],\n# [4, 8, 12, 16, 20],\n# [5, 10, 15, 20, 25]]\n```\n\nDictionary\n-----\n\nDictionary Comprehensions\n\n```python\n{c: ord(c) - 96 for c in string.ascii_lowercase[:26]}\n\n# output\n# {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}\n```\n\nSet\n-----\n\nSet Comprehensions\n\n```python\nnumbers = [2, 2, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14]\nuniqueEvenNumbers = {num for num in numbers if num % 2 == 0}\n\n# output\n# set([2, 4, 6, 8, 10, 12, 14])\n\nuniqueNumbers = set(numbers)\n\n# output\n# set([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])\n```\n\nmap() Function\n============\n\n```python\nmap(function, list)\n```\n\n```python\nnumbers = [1, 2, 3, 4, 5]\nsquared = list(map(lambda n: n*n, numbers))\n\n# output\n# [1, 4, 9, 16, 25]\n```\n\nfilter() Function\n============\n\n```python\nfilter(function, list)\n```\n\n```python\nnumbers = [1, 2, 3, 4, 5]\nodd = list(filter(lambda n: n % 2 != 0, numbers))\n\n# output\n# [1, 3, 5]\n```\n\nreduce() Function\n============\n\n```python\nreduce(function, list)\n```\n\n```python\nnumbers = [1, 2, 3, 4, 5]\nsum = reduce(lambda x, y: x + y, numbers\n\n# output\n# 15\n```\n\nzip() Function\n============\n\nCreates an iterator of tuples.\n\n```python\nzip(iterator1, iterator2, iterator3 ...)\n```\n\n```python\na = ['a', 'b', 'c']\nb = [1, 2, 3]\n\nzip(a, b)\n\n# output\n# [('a', 1), ('b', 2), ('c', 3)]\n```\n\ntuples to list\n\n```python\nlist(map(list, zip(a, b)))\n\n# output\n# [['a', 1], ['b', 2], ['c', 3]]\n```\n\nformat() function\n============\n\n```python\n\"{:{width}.{prec}f}\".format(10.344, width=10, prec=6)\n\n# output\n# ' 10.344000'\n```\n\n\nMiscellaneous\n============\n\nGet the number of bits in an integer in binary, excluding the sign and leading zeros.\n-----\n\n```python\nn.bit_length()\n```\n\nSwap two variables in one line\n-----\n\n```python\na, b = b, a\n```\n\nMy Python Articles\n============\n1. [How To Run a Python Script Using a Docker Container](https://towardsdatascience.com/how-to-run-a-python-script-using-a-docker-container-ea248e618e32)\n2. [How To Create a Twitter Bot in Python](https://levelup.gitconnected.com/how-to-create-a-twitter-bot-in-python-bf49a384905f)\n3. [How To Extract Text From Images Using Tesseract OCR Engine and Python](https://towardsdatascience.com/how-to-extract-text-from-images-using-tesseract-ocr-engine-and-python-22934125fdd5)\n4. [How to Connect to a PostgreSQL Database With a Python Serverless Function](https://towardsdatascience.com/how-to-connect-to-a-postgresql-database-with-a-python-serverless-function-f5f3b244475)\n5. [How to Deploy a Python Serverless Function to Vercel](https://towardsdatascience.com/how-to-deploy-a-python-serverless-function-to-vercel-f43c8ca393a0)\n6. [How to Dockerize an Existing Flask Application](https://towardsdatascience.com/how-to-dockerize-an-existing-flask-application-115408463e1c)\n7. [How To Create a Docker Image From a Container](https://python.plainenglish.io/how-to-create-a-docker-image-from-a-container-402f70f3dbf0)\n\nBooks and other resources\n============\n1. TODO\n\nBug Reports and Feature Requests\n============\nPlease create an issue with as much information you can. Thank you.\n\nAuthor\n============\nMahbub Zaman (https://mahbub.ninja)\n\nLicense\n============\nMIT License\n","funding_links":[],"categories":["Uncategorized"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flifeparticle%2FPython-Cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flifeparticle%2FPython-Cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flifeparticle%2FPython-Cheatsheet/lists"}