{"id":13404449,"url":"https://github.com/aneagoie/ztm-python-cheat-sheet","last_synced_at":"2026-01-29T09:41:31.214Z","repository":{"id":38716281,"uuid":"210066928","full_name":"aneagoie/ztm-python-cheat-sheet","owner":"aneagoie","description":null,"archived":false,"fork":false,"pushed_at":"2025-09-21T17:12:21.000Z","size":57,"stargazers_count":2589,"open_issues_count":7,"forks_count":1410,"subscribers_count":192,"default_branch":"master","last_synced_at":"2025-09-21T19:14:05.297Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://zerotomastery.io/courses/python/cheatsheet/","language":null,"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/aneagoie.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-09-21T23:51:14.000Z","updated_at":"2025-09-21T18:10:19.000Z","dependencies_parsed_at":"2024-03-27T14:30:19.319Z","dependency_job_id":"cffdf59a-1674-4e78-a22b-587fe9a56576","html_url":"https://github.com/aneagoie/ztm-python-cheat-sheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/aneagoie/ztm-python-cheat-sheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aneagoie%2Fztm-python-cheat-sheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aneagoie%2Fztm-python-cheat-sheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aneagoie%2Fztm-python-cheat-sheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aneagoie%2Fztm-python-cheat-sheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aneagoie","download_url":"https://codeload.github.com/aneagoie/ztm-python-cheat-sheet/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aneagoie%2Fztm-python-cheat-sheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28874254,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-29T07:35:32.468Z","status":"ssl_error","status_checked_at":"2026-01-29T07:33:31.463Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":[],"created_at":"2024-07-30T19:01:45.337Z","updated_at":"2026-01-29T09:41:31.195Z","avatar_url":"https://github.com/aneagoie.png","language":null,"readme":"Python ZTM Cheatsheet 💻🚀\n===============================\n\nWe created this Python Cheat Sheet initially for students of [Complete Python Developer: Zero to Mastery](https://zerotomastery.io/courses/learn-python/) but we're now sharing it with any Python beginners to help them learn and remember common Python syntax and with intermediate and advanced Python developers as a handy reference. If you'd like to download a PDF version of this Python Cheat Sheet, you can get it [here](https://zerotomastery.io/courses/python/cheatsheet/?utm_source=github\u0026utm_medium=ztm-python-cheat-sheet)!!\n\nContents\n--------\n**Python Types:** **[`Numbers`](#numbers)__,__[`Strings`](#strings)__,__[`Boolean`](#boolean)__,__[`Lists`](#lists)__,__[`Dictionaries`](#dictionaries)__,__ [`Tuples`](#tuples)__,__[`Sets`](#sets)__,__[`None`](#none)**  \n\n**Python Basics:** **[`Comparison Operators`](#comparison-operators)__,__[`Logical Operators`](#logical-operators)__,__[`Loops`](#loops)__,__[`Range`](#range)__,__[`Enumerate`](#enumerate)__,__[`Counter`](#counter)__,__[`Named Tuple`](#named-tuple)__,__[`OrderedDict`](#ordereddict)**    \n\n**Functions:** **[`Functions`](#functions)__,__[`Lambda`](#lambda)__,__[`Comprehensions`](#comprehensions)__,__[`Map,Filter,Reduce`](#map-filter-reduce)__,__[`Ternary`](#ternary-condition)__,__[`Any,All`](#any-all)__,__[`Closures`](#closures)__,__[`Scope`](#scope)**    \n\n**Advanced Python:** **[`Modules`](#modules)__,__[`Iterators`](#iterators)__,__[`Generators`](#generators)__,__[`Decorators`](#decorators)__,__[`Class`](#class)__,__[`Exceptions`](#exceptions)__,__[`Command Line Arguments`](#command-line-arguments)__,__[`File IO`](#file-io)__,__[`Useful Libraries`](#useful-libraries)**  \n\n\nNumbers\n----\n**python's 2 main types for Numbers is int and float (or integers and floating point numbers)**\n```python\ntype(1)   # int \ntype(-10) # int\ntype(0)   # int\ntype(0.0) # float\ntype(2.2) # float\ntype(4E2) # float - 4*10 to the power of 2\n```\n\n```python\n# Arithmetic\n10 + 3  # 13\n10 - 3  # 7\n10 * 3  # 30\n10 ** 3 # 1000\n10 / 3  # 3.3333333333333335\n10 // 3 # 3 --\u003e floor division - no decimals and returns an int\n10 % 3  # 1 --\u003e modulo operator - return the remainder. Good for deciding if number is even or odd\n```\n\n```python\n# Basic Functions\npow(5, 2)      # 25 --\u003e like doing 5**2\nabs(-50)       # 50\nround(5.46)    # 5\nround(5.468, 2)# 5.47 --\u003e round to nth digit\nbin(512)       # '0b1000000000' --\u003e  binary format\nhex(512)       # '0x200' --\u003e hexadecimal format\n```\n\n```python\n# Converting Strings to Numbers\nage = input(\"How old are you?\")\nage = int(age)\npi = input(\"What is the value of pi?\")\npi = float(pi)\n```\n\nStrings\n----\n**strings in python are stored as sequences of letters in memory**\n```python\ntype('Hellloooooo') # str\n\n'I\\'m thirsty'\n\"I'm thirsty\"\n\"\\n\" # new line\n\"\\t\" # adds a tab\n\n'Hey you!'[4] # y\nname = 'Andrei Neagoie'\nname[4]     # e\nname[:]     # Andrei Neagoie\nname[1:]    # ndrei Neagoie\nname[:1]    # A\nname[-1]    # e\nname[::1]   # Andrei Neagoie\nname[::-1]  # eiogaeN ierdnA\nname[0:10:2]# Ade e\n# : is called slicing and has the format [ start : end : step ]\n\n'Hi there ' + 'Timmy' # 'Hi there Timmy' --\u003e This is called string concatenation\n'*'*10 # **********\n```\n\n```python\n# Basic Functions\nlen('turtle') # 6\n\n# Basic Methods\n'  I am alone '.strip()               # 'I am alone' --\u003e Strips all whitespace characters from both ends.\n'On an island'.strip('d')             # 'On an islan' --\u003e # Strips all passed characters from both ends.\n'but life is good!'.split()           # ['but', 'life', 'is', 'good!']\n'Help me'.replace('me', 'you')        # 'Help you' --\u003e Replaces first with second param\n'Need to make fire'.startswith('Need')# True\n'and cook rice'.endswith('rice')      # True\n'still there?'.upper()                # STILL THERE?\n'HELLO?!'.lower()                     # hello?!\n'ok, I am done.'.capitalize()         # 'Ok, I am done.'\n'oh hi there'.count('e')              # 2\n'bye bye'.index('e')                  # 2\n'oh hi there'.find('i')               # 4 --\u003e returns the starting index position of the first occurrence\n'oh hi there'.find('a')               # -1\n'oh hi there'.index('a')              # Raises ValueError\n```\n\n```python\n# String Formatting\nname1 = 'Andrei'\nname2 = 'Sunny'\nprint(f'Hello there {name1} and {name2}')       # Hello there Andrei and Sunny - Newer way to do things as of python 3.6\nprint('Hello there {} and {}'.format(name1, name2))# Hello there Andrei and Sunny\nprint('Hello there %s and %s' %(name1, name2))  # Hello there Andrei and Sunny --\u003e you can also use %d, %f, %r for integers, floats, string representations of objects respectively\n```\n\n```python\n# Palindrome check\nword = 'reviver'\np = bool(word.find(word[::-1]) + 1)\nprint(p) # True\n```\n\nBoolean\n----\n**True or False. Used in a lot of comparison and logical operations in Python**\n```python\nbool(True)\nbool(False)\n\n# all of the below evaluate to False. Everything else will evaluate to True in Python.\nprint(bool(None))\nprint(bool(False))\nprint(bool(0))\nprint(bool(0.0))\nprint(bool([]))\nprint(bool({}))\nprint(bool(()))\nprint(bool(''))\nprint(bool(range(0)))\nprint(bool(set()))\n\n# See Logical Operators and Comparison Operators section for more on booleans.\n```\n\nLists\n----\n**Unlike strings, lists are mutable sequences in python**\n```python\nmy_list = [1, 2, '3', True]# We assume this list won't mutate for each example below\nlen(my_list)               # 4\nmy_list.index('3')         # 2\nmy_list.count(2)           # 1 --\u003e count how many times 2 appears\n\nmy_list[3]                 # True\nmy_list[1:]                # [2, '3', True]\nmy_list[:1]                # [1]\nmy_list[-1]                # True\nmy_list[::1]               # [1, 2, '3', True]\nmy_list[::-1]              # [True, '3', 2, 1]\nmy_list[0:3:2]             # [1, '3']\n\n# : is called slicing and has the format [ start : end : step ]\n```\n\n```python\n# Add to List\nmy_list * 2                # [1, 2, '3', True, 1, 2, '3', True]\nmy_list + [100]            # [1, 2, '3', True, 100] --\u003e doesn't mutate original list, creates new one\nmy_list.append(100)        # None --\u003e Mutates original list to [1, 2, '3', True, 100]          # Or: \u003clist\u003e += [\u003cel\u003e]\nmy_list.extend([100, 200]) # None --\u003e Mutates original list to [1, 2, '3', True, 100, 200]\nmy_list.insert(2, '!!!')   # None --\u003e  [1, 2, '!!!', '3', True] - Inserts item at index and moves the rest to the right.\n\n' '.join(['Hello','There'])# 'Hello There' --\u003e Joins elements using string as separator.\n```\n\n```python\n# Copy a List\nbasket = ['apples', 'pears', 'oranges']\nnew_basket = basket.copy()\nnew_basket2 = basket[:]\n```\n```python\n# Remove from List\n[1,2,3].pop()    # 3 --\u003e mutates original list, default index in the pop method is -1 (the last item)\n[1,2,3].pop(1)   # 2 --\u003e mutates original list\n[1,2,3].remove(2)# None --\u003e [1,3] Removes first occurrence of item or raises ValueError.\n[1,2,3].clear()  # None --\u003e mutates original list and removes all items: []\ndel [1,2,3][0]   # None --\u003e removes item on index 0 or raises IndexError\n```\n\n```python\n# Ordering\n[1,2,5,3].sort()         # None --\u003e Mutates list to [1, 2, 3, 5]\n[1,2,5,3].sort(reverse=True) # None --\u003e Mutates list to [5, 3, 2, 1]\n[1,2,5,3].reverse()      # None --\u003e Mutates list to [3, 5, 2, 1]\nsorted([1,2,5,3])        # [1, 2, 3, 5] --\u003e new list created\nmy_list = [(4,1),(2,4),(2,5),(1,6),(8,9)]\nsorted(my_list,key=lambda x: int(x[0])) # [(1, 6), (2, 4), (2, 5), (4, 1), (8, 9)] --\u003e sort the list by 1st (0th index) value of the tuple\nlist(reversed([1,2,5,3]))# [3, 5, 2, 1] --\u003e reversed() returns an iterator\n```\n\n```python\n# Useful operations\n1 in [1,2,5,3]  # True\nmin([1,2,3,4,5])# 1\nmax([1,2,3,4,5])# 5\nsum([1,2,3,4,5])# 15\n```\n\n```python\n# Get First and Last element of a list\nmList = [63, 21, 30, 14, 35, 26, 77, 18, 49, 10]\nfirst, *x, last = mList\nprint(first) #63\nprint(last) #10\n```\n\n```python\n# Matrix\nmatrix = [[1,2,3], [4,5,6], [7,8,9]]\nmatrix[2][0] # 7 --\u003e Grab first first of the third item in the matrix object\n\n# Looping through a matrix by rows:\nmx = [[1,2,3],[4,5,6]]\nfor row in range(len(mx)):\n\tfor col in range(len(mx[0])):\n\t\tprint(mx[row][col]) # 1 2 3 4 5 6\n    \n# Transform into a list:\n[mx[row][col] for row in range(len(mx)) for col in range(len(mx[0]))] # [1,2,3,4,5,6]\n\n# Combine columns with zip and *:\n[x for x in zip(*mx)] # [(1, 3), (2, 4)]\n\n```\n\n```python\n# List Comprehensions\n# new_list[\u003caction\u003e for \u003citem\u003e in \u003citerator\u003e if \u003csome condition\u003e]\na = [i for i in 'hello']                  # ['h', 'e', 'l', 'l', '0']\nb = [i*2 for i in [1,2,3]]                # [2, 4, 6]\nc = [i for i in range(0,10) if i % 2 == 0]# [0, 2, 4, 6, 8]\n```\n\n```python\n# Advanced Functions\nlist_of_chars = list('Helloooo')                                   # ['H', 'e', 'l', 'l', 'o', 'o', 'o', 'o']\nsum_of_elements = sum([1,2,3,4,5])                                 # 15\nelement_sum = [sum(pair) for pair in zip([1,2,3],[4,5,6])]         # [5, 7, 9]\nsorted_by_second = sorted(['hi','you','man'], key=lambda el: el[1])# ['man', 'hi', 'you']\nsorted_by_key = sorted([\n                       {'name': 'Bina', 'age': 30},\n                       {'name':'Andy', 'age': 18},\n                       {'name': 'Zoey', 'age': 55}],\n                       key=lambda el: (el['name']))# [{'name': 'Andy', 'age': 18}, {'name': 'Bina', 'age': 30}, {'name': 'Zoey', 'age': 55}]\n```\n\n```python\n# Read line of a file into a list\nwith open(\"myfile.txt\") as f:\n  lines = [line.strip() for line in f]\n```\n\nDictionaries\n----------\n**Also known as mappings or hash tables. They are key value pairs that are guaranteed to retain order of insertion starting from Python 3.7**\n```python\nmy_dict = {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False}\nmy_dict['name']                      # Andrei Neagoie\nlen(my_dict)                         # 3\nlist(my_dict.keys())                 # ['name', 'age', 'magic_power']\nlist(my_dict.values())               # ['Andrei Neagoie', 30, False]\nlist(my_dict.items())                # [('name', 'Andrei Neagoie'), ('age', 30), ('magic_power', False)]\nmy_dict['favourite_snack'] = 'Grapes'# {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes'}\nmy_dict.get('age')                   # 30 --\u003e Returns None if key does not exist.\nmy_dict.get('ages', 0 )              # 0 --\u003e Returns default (2nd param) if key is not found\n\n#Remove key\ndel my_dict['name']\nmy_dict.pop('name', None)\n```\n\n```python\nmy_dict.update({'cool': True})                                         # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}\n{**my_dict, **{'cool': True} }                                         # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}\nnew_dict = dict([['name','Andrei'],['age',32],['magic_power',False]])  # Creates a dict from collection of key-value pairs.\nnew_dict = dict(zip(['name','age','magic_power'],['Andrei',32, False]))# Creates a dict from two collections.\nnew_dict = my_dict.pop('favourite_snack')                              # Removes item from dictionary.\n```\n\n```python\n# Dictionary Comprehension\n{key: value for key, value in new_dict.items() if key == 'age' or key == 'name'} # {'name': 'Andrei', 'age': 32} --\u003e Filter dict by keys\n```\n\nTuples\n----\n**Like lists, but they are used for immutable thing (that don't change)**\n```python\nmy_tuple = ('apple','grapes','mango', 'grapes')\napple, grapes, mango, grapes = my_tuple# Tuple unpacking\nlen(my_tuple)                          # 4\nmy_tuple[2]                            # mango\nmy_tuple[-1]                           # 'grapes'\n```\n\n```python\n# Immutability\nmy_tuple[1] = 'donuts'  # TypeError\nmy_tuple.append('candy')# AttributeError\n```\n\n```python\n# Methods\nmy_tuple.index('grapes') # 1\nmy_tuple.count('grapes') # 2\n```\n\n```python\n# Zip\nlist(zip([1,2,3], [4,5,6])) # [(1, 4), (2, 5), (3, 6)]\n```\n\n```python\n# unzip\nz = [(1, 2), (3, 4), (5, 6), (7, 8)] # Some output of zip() function\nunzip = lambda z: list(zip(*z))\nunzip(z)\n```\n\nSets\n---\n**Unorderd collection of unique elements.**\n```python\nmy_set = set()\nmy_set.add(1)  # {1}\nmy_set.add(100)# {1, 100}\nmy_set.add(100)# {1, 100} --\u003e no duplicates!\n```\n\n```python\nnew_list = [1,2,3,3,3,4,4,5,6,1]\nset(new_list)           # {1, 2, 3, 4, 5, 6}\n\nmy_set.remove(100)      # {1} --\u003e Raises KeyError if element not found\nmy_set.discard(100)     # {1} --\u003e Doesn't raise an error if element not found\nmy_set.clear()          # {}\nnew_set = {1,2,3}.copy()# {1,2,3}\n```\n\n```python\nset1 = {1,2,3}\nset2 = {3,4,5}\nset3 = set1.union(set2)               # {1,2,3,4,5}\nset4 = set1.intersection(set2)        # {3}\nset5 = set1.difference(set2)          # {1, 2}\nset6 = set1.symmetric_difference(set2)# {1, 2, 4, 5}\nset1.issubset(set2)                   # False\nset1.issuperset(set2)                 # False\nset1.isdisjoint(set2)                 # False --\u003e return True if two sets have a null intersection.\n\n```\n\n```python\n# Frozenset\n# hashable --\u003e it can be used as a key in a dictionary or as an element in a set.\n\u003cfrozenset\u003e = frozenset(\u003ccollection\u003e)\n```\n\nNone\n----\n**None is used for absence of a value and can be used to show nothing has been assigned to an object**\n```python\ntype(None) # NoneType\na = None\n```\n\nComparison Operators\n--------\n```python\n==                   # equal values\n!=                   # not equal\n\u003e                    # left operand is greater than right operand\n\u003c                    # left operand is less than right operand\n\u003e=                   # left operand is greater than or equal to right operand\n\u003c=                   # left operand is less than or equal to right operand\n\u003celement\u003e is \u003celement\u003e # check if two operands refer to same object in memory\n```\n\nLogical Operators\n--------\n```python\n1 \u003c 2 and 4 \u003e 1 # True\n1 \u003e 3 or 4 \u003e 1  # True\n1 is not 4      # True\nnot True        # False\n1 not in [2,3,4]# True\n\nif \u003ccondition that evaluates to boolean\u003e:\n  # perform action1\nelif \u003ccondition that evaluates to boolean\u003e:\n  # perform action2\nelse:\n  # perform action3\n```\n\nLoops\n--------\n```python\nmy_list = [1,2,3]\nmy_tuple = (1,2,3)\nmy_list2 = [(1,2), (3,4), (5,6)]\nmy_dict = {'a': 1, 'b': 2. 'c': 3}\n\nfor num in my_list:\n    print(num) # 1, 2, 3\n\nfor num in my_tuple:\n    print(num) # 1, 2, 3\n\nfor num in my_list2:\n    print(num) # (1,2), (3,4), (5,6)\n\nfor num in '123':\n    print(num) # 1, 2, 3\n\nfor idx,value in enumerate(my_list):\n    print(idx) # get the index of the item\n    print(value) # get the value\n\nfor k,v in my_dict.items(): # Dictionary Unpacking\n    print(k) # 'a', 'b', 'c'\n    print(v) # 1, 2, 3\n\nwhile \u003ccondition that evaluates to boolean\u003e:\n  # action\n  if \u003ccondition that evaluates to boolean\u003e:\n    break # break out of while loop\n  if \u003ccondition that evaluates to boolean\u003e:\n    continue # continue to the next line in the block\n```\n\n```python\n# waiting until user quits\nmsg = ''\nwhile msg != 'quit':\n    msg = input(\"What should I do?\")\n    print(msg)\n```\n\nRange\n-----\n```python\nrange(10)          # range(0, 10) --\u003e 0 to 9\nrange(1,10)        # range(1, 10)\nlist(range(0,10,2))# [0, 2, 4, 6, 8]\n```\n\nEnumerate\n---------\n```python\nfor i, el in enumerate('helloo'):\n  print(f'{i}, {el}')\n# 0, h\n# 1, e\n# 2, l\n# 3, l\n# 4, o\n# 5, o\n```\n\nCounter\n-----\n```python\nfrom collections import Counter\ncolors = ['red', 'blue', 'yellow', 'blue', 'red', 'blue']\ncounter = Counter(colors)# Counter({'blue': 3, 'red': 2, 'yellow': 1})\ncounter.most_common()[0] # ('blue', 3)\n```\n\nNamed Tuple\n-----------\n* **Tuple is an immutable and hashable list.**\n* **Named tuple is its subclass with named elements.**\n\n```python\nfrom collections import namedtuple\nPoint = namedtuple('Point', 'x y')\np = Point(1, y=2)# Point(x=1, y=2)\np[0]             # 1\np.x              # 1\ngetattr(p, 'y')  # 2\np._fields        # Or: Point._fields #('x', 'y')\n```\n\n```python\nfrom collections import namedtuple\nPerson = namedtuple('Person', 'name height')\nperson = Person('Jean-Luc', 187)\nf'{person.height}'           # '187'\n'{p.height}'.format(p=person)# '187'\n```\n\nOrderedDict\n--------\n* **Maintains order of insertion**\n```python\nfrom collections import OrderedDict\n# Store each person's languages, keeping # track of who responded first. \nprogrammers = OrderedDict()\nprogrammers['Tim'] = ['python', 'javascript']\nprogrammers['Sarah'] = ['C++']\nprogrammers['Bia'] = ['Ruby', 'Python', 'Go']\n\nfor name, langs in programmers.items():\n    print(name + '--\u003e')\n    for lang in langs:\n      print('\\t' + lang)\n\n```\n\nFunctions\n-------\n\n#### \\*args and \\*\\*kwargs\n**Splat (\\*) expands a collection into positional arguments, while splatty-splat (\\*\\*) expands a dictionary into keyword arguments.**\n```python\nargs   = (1, 2)\nkwargs = {'x': 3, 'y': 4, 'z': 5}\nsome_func(*args, **kwargs) # same as some_func(1, 2, x=3, y=4, z=5)\n```\n\n#### \\* Inside Function Definition\n**Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.**\n```python\ndef add(*a):\n    return sum(a)\n\nadd(1, 2, 3) # 6\n```\n\n##### Ordering of parameters:\n```python\ndef f(*args):                  # f(1, 2, 3)\ndef f(x, *args):               # f(1, 2, 3)\ndef f(*args, z):               # f(1, 2, z=3)\ndef f(x, *args, z):            # f(1, 2, z=3)\n\ndef f(**kwargs):               # f(x=1, y=2, z=3)\ndef f(x, **kwargs):            # f(x=1, y=2, z=3) | f(1, y=2, z=3)\n\ndef f(*args, **kwargs):        # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)\ndef f(x, *args, **kwargs):     # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)\ndef f(*args, y, **kwargs):     # f(x=1, y=2, z=3) | f(1, y=2, z=3)\ndef f(x, *args, z, **kwargs):  # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)\n```\n\n#### Other Uses of \\*\n```python\n[*[1,2,3], *[4]]                # [1, 2, 3, 4]\n{*[1,2,3], *[4]}                # {1, 2, 3, 4}\n(*[1,2,3], *[4])                # (1, 2, 3, 4)\n{**{'a': 1, 'b': 2}, **{'c': 3}}# {'a': 1, 'b': 2, 'c': 3}\n```\n\n```python\nhead, *body, tail = [1,2,3,4,5]\n```\n\n\nLambda\n------\n```python\n# lambda: \u003creturn_value\u003e\n# lambda \u003cargument1\u003e, \u003cargument2\u003e: \u003creturn_value\u003e\n```\n\n```python\n# Factorial\nfrom functools import reduce\n\nn = 3\nfactorial = reduce(lambda x, y: x*y, range(1, n+1))\nprint(factorial) #6\n```\n\n```python\n# Fibonacci\nfib = lambda n : n if n \u003c= 1 else fib(n-1) + fib(n-2)\nresult = fib(10)\nprint(result) #55\n```\n\nComprehensions\n------\n```python\n\u003clist\u003e = [i+1 for i in range(10)]         # [1, 2, ..., 10]\n\u003cset\u003e  = {i for i in range(10) if i \u003e 5}  # {6, 7, 8, 9}\n\u003citer\u003e = (i+5 for i in range(10))         # (5, 6, ..., 14)\n\u003cdict\u003e = {i: i*2 for i in range(10)}      # {0: 0, 1: 2, ..., 9: 18}\n```\n\n```python\noutput = [i+j for i in range(3) for j in range(3)] # [0, 1, 2, 1, 2, 3, 2, 3, 4]\n\n# Is the same as:\noutput = []\nfor i in range(3):\n  for j in range(3):\n    output.append(i+j)\n```\n\nTernary Condition\n-------\n```python\n# \u003cexpression_if_true\u003e if \u003ccondition\u003e else \u003cexpression_if_false\u003e\n\n[a if a else 'zero' for a in [0, 1, 0, 3]] # ['zero', 1, 'zero', 3]\n```\n\nMap Filter Reduce\n------\n```python\nfrom functools import reduce\nlist(map(lambda x: x + 1, range(10)))            # [1, 2, 3, 4, 5, 6, 7, 8, 9,10]\nlist(filter(lambda x: x \u003e 5, range(10)))         # (6, 7, 8, 9)\nreduce(lambda acc, x: acc + x, range(10))        # 45\n```\n\nAny All\n------\n```python\nany([False, True, False])# True if at least one item in collection is truthy, False if empty.\nall([True,1,3,True])     # True if all items in collection are true\n```\n\n\nClosures\n-------\n**We have a closure in Python when:**\n* **A nested function references a value of its enclosing function and then**\n* **the enclosing function returns the nested function.**\n\n```python\ndef get_multiplier(a):\n    def out(b):\n        return a * b\n    return out\n```\n\n```python\n\u003e\u003e\u003e multiply_by_3 = get_multiplier(3)\n\u003e\u003e\u003e multiply_by_3(10)\n30\n```\n\n* **If multiple nested functions within enclosing function reference the same value, that value gets shared.**\n* **To dynamically access function's first free variable use `'\u003cfunction\u003e.__closure__[0].cell_contents'`.**\n\n\n\n### Scope\n**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.**\n\n```python\ndef get_counter():\n    i = 0\n    def out():\n        nonlocal i\n        i += 1\n        return i\n    return out\n```\n\n```python\n\u003e\u003e\u003e counter = get_counter()\n\u003e\u003e\u003e counter(), counter(), counter()\n(1, 2, 3)\n```\n\nModules\n----\n```python\nif __name__ == '__main__': # Runs main() if file wasn't imported.\n    main()\n```\n\n```python\nimport \u003cmodule_name\u003e\nfrom \u003cmodule_name\u003e import \u003cfunction_name\u003e\nimport \u003cmodule_name\u003e as m\nfrom \u003cmodule_name\u003e import \u003cfunction_name\u003e as m_function\nfrom \u003cmodule_name\u003e import *\n```\n\n\nIterators\n--------\n**In this cheatsheet `'\u003ccollection\u003e'` can also mean an iterator.**\n\n```python\n\u003citer\u003e = iter(\u003ccollection\u003e)\n\u003citer\u003e = iter(\u003cfunction\u003e, to_exclusive)     # Sequence of return values until 'to_exclusive'.\n\u003cel\u003e   = next(\u003citer\u003e [, default])           # Raises StopIteration or returns 'default' on end.\n```\n\n\nGenerators\n---------\n**Convenient way to implement the iterator protocol.**\n\n```python\ndef count(start, step):\n    while True:\n        yield start\n        start += step\n```\n\n```python\n\u003e\u003e\u003e counter = count(10, 2)\n\u003e\u003e\u003e next(counter), next(counter), next(counter)\n(10, 12, 14)\n```\n\n\nDecorators\n---------\n**A decorator takes a function, adds some functionality and returns it.**\n\n```python\n@decorator_name\ndef function_that_gets_passed_to_decorator():\n    ...\n```\n\n**Example Decorator: timing performance using a decorator.**\n* **The functools decorator `@functools.wraps` is used to maintain function naming and \ndocumentation of the function within the decorator.**\n\n```python\nfrom time import time \nimport functools\n\ndef performance(func):\n\n    @functools.wraps()\n    def wrapper(*args, **kwargs):\n        t1 = time()\n        result = func(*args, **kwargs)\n        t2 = time() \n        print(f\"Took: {t2 - t1} ms\")\n        return result\n    return wrapper\n\n# calling a function with the decorator \n@performance\ndef long_time():\n    print(sum(i*i for i in range(10000)))\n``` \n\n### Debugger Example\n**Decorator that prints function's name every time it gets called.**\n\n```python\nfrom functools import wraps\n\ndef debug(func):\n    @wraps(func)\n    def out(*args, **kwargs):\n        print(func.__name__)\n        return func(*args, **kwargs)\n    return out\n\n@debug\ndef add(x, y):\n    return x + y\n```\n* **Wraps is a helper decorator that copies metadata of function add() to function out().**\n* **Without it `'add.__name__'` would return `'out'`.**\n\n\n\nClass\n-----\n**User defined objects are created using the class keyword**\n\n```python\nclass \u003cname\u003e:\n    age = 80 # Class Object Attribute\n    def __init__(self, a):\n        self.a = a # Object Attribute\n\n    @classmethod\n    def get_class_name(cls):\n        return cls.__name__\n```\n\n### Inheritance\n```python\nclass Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age  = age\n\nclass Employee(Person):\n    def __init__(self, name, age, staff_num):\n        super().__init__(name, age)\n        self.staff_num = staff_num\n```\n\n### Multiple Inheritance\n```python\nclass A: pass\nclass B: pass\nclass C(A, B): pass\n```\n\n**MRO determines the order in which parent classes are traversed when searching for a method:**\n```python\n\u003e\u003e\u003e C.mro()\n[\u003cclass 'C'\u003e, \u003cclass 'A'\u003e, \u003cclass 'B'\u003e, \u003cclass 'object'\u003e]\n```\n\nExceptions\n----------\n\n```python\ntry:\n  5/0\nexcept ZeroDivisionError:\n  print(\"No division by zero!\")\n```\n\n```python\nwhile True:\n  try:\n    x = int(input('Enter your age: '))\n  except ValueError:\n    print('Oops!  That was no valid number.  Try again...')\n  else: # code that depends on the try block running successfully should be placed in the else block.\n    print('Carry on!')\n    break\n```\n\n### Raising Exception\n```python\nraise ValueError('some error message')\n```\n\n### Finally\n```python\ntry:\n  raise KeyboardInterrupt\nexcept:\n  print('oops')\nfinally:\n  print('All done!')\n\n```\n\n\n\nCommand Line Arguments\n----------------------\n```python\nimport sys\nscript_name = sys.argv[0]\narguments   = sys.argv[1:]\n```\n\nFile IO\n----\n**Opens a file and returns a corresponding file object.**\n\n```python\n\u003cfile\u003e = open('\u003cpath\u003e', mode='r', encoding=None)\n```\n\n### Modes\n* **`'r'`  - Read (default).**\n* **`'w'`  - Write (truncate).**\n* **`'x'`  - Write or fail if the file already exists.**\n* **`'a'`  - Append.**\n* **`'w+'` - Read and write (truncate).**\n* **`'r+'` - Read and write from the start.**\n* **`'a+'` - Read and write from the end.**\n* **`'t'`  - Text mode (default).**\n* **`'b'`  - Binary mode.**\n\n### File\n```python\n\u003cfile\u003e.seek(0)                      # Moves to the start of the file.\n```\n\n```python\n\u003cstr/bytes\u003e = \u003cfile\u003e.readline()     # Returns a line.\n\u003clist\u003e      = \u003cfile\u003e.readlines()    # Returns a list of lines.\n```\n\n```python\n\u003cfile\u003e.write(\u003cstr/bytes\u003e)           # Writes a string or bytes object.\n\u003cfile\u003e.writelines(\u003clist\u003e)           # Writes a list of strings or bytes objects.\n```\n* **Methods do not add or strip trailing newlines.**\n\n### Read Text from File\n```python\ndef read_file(filename):\n    with open(filename, encoding='utf-8') as file:\n        return file.readlines() # or read()\n\nfor line in read_file(filename):\n  print(line)\n```\n\n### Write Text to File\n```python\ndef write_to_file(filename, text):\n    with open(filename, 'w', encoding='utf-8') as file:\n        file.write(text)\n```\n\n### Append Text to File\n```python\ndef append_to_file(filename, text):\n    with open(filename, 'a', encoding='utf-8') as file:\n        file.write(text)\n```\n\nUseful Libraries\n=========\n\nCSV\n---\n```python\nimport csv\n```\n\n### Read Rows from CSV File\n```python\ndef read_csv_file(filename):\n    with open(filename, encoding='utf-8') as file:\n        return csv.reader(file, delimiter=';')\n```\n\n### Write Rows to CSV File\n```python\ndef write_to_csv_file(filename, rows):\n    with open(filename, 'w', encoding='utf-8') as file:\n        writer = csv.writer(file, delimiter=';')\n        writer.writerows(rows)\n```\n\n\nJSON\n----\n```python\nimport json\n\u003cstr\u003e    = json.dumps(\u003cobject\u003e, ensure_ascii=True, indent=None)\n\u003cobject\u003e = json.loads(\u003cstr\u003e)\n```\n\n### Read Object from JSON File\n```python\ndef read_json_file(filename):\n    with open(filename, encoding='utf-8') as file:\n        return json.load(file)\n```\n\n### Write Object to JSON File\n```python\ndef write_to_json_file(filename, an_object):\n    with open(filename, 'w', encoding='utf-8') as file:\n        json.dump(an_object, file, ensure_ascii=False, indent=2)\n```\n\n\nPickle\n------\n```python\nimport pickle\n\u003cbytes\u003e  = pickle.dumps(\u003cobject\u003e)\n\u003cobject\u003e = pickle.loads(\u003cbytes\u003e)\n```\n\n### Read Object from File\n```python\ndef read_pickle_file(filename):\n    with open(filename, 'rb') as file:\n        return pickle.load(file)\n```\n\n### Write Object to File\n```python\ndef write_to_pickle_file(filename, an_object):\n    with open(filename, 'wb') as file:\n        pickle.dump(an_object, file)\n```\n\n\nProfile\n-------\n### Basic\n```python\nfrom time import time\nstart_time = time()  # Seconds since\n...\nduration = time() - start_time\n```\n\n### Math\n```python\nfrom math import e, pi\nfrom math import cos, acos, sin, asin, tan, atan, degrees, radians\nfrom math import log, log10, log2\nfrom math import inf, nan, isinf, isnan\n```\n\n### Statistics\n```python\nfrom statistics import mean, median, variance, pvariance, pstdev\n```\n\n### Random\n```python\nfrom random import random, randint, choice, shuffle\nrandom() # random float between 0 and 1\nrandint(0, 100) # random integer between 0 and 100\nrandom_el = choice([1,2,3,4]) # select a random element from list\nshuffle([1,2,3,4]) # shuffles a list\n```\n\n\nDatetime\n--------\n* **Module 'datetime' provides 'date' `\u003cD\u003e`, 'time' `\u003cT\u003e`, 'datetime' `\u003cDT\u003e` and 'timedelta' `\u003cTD\u003e` classes. All are immutable and hashable.**\n* **Time and datetime can be 'aware' `\u003ca\u003e`, meaning they have defined timezone, or 'naive' `\u003cn\u003e`, meaning they don't.**\n* **If object is naive it is presumed to be in system's timezone.**\n\n```python\nfrom datetime import date, time, datetime, timedelta\nfrom dateutil.tz import UTC, tzlocal, gettz\n```\n\n### Constructors\n```python\n\u003cD\u003e  = date(year, month, day)\n\u003cT\u003e  = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)\n\u003cDT\u003e = datetime(year, month, day, hour=0, minute=0, second=0, ...)\n\u003cTD\u003e = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,\n                 minutes=0, hours=0, weeks=0)\n```\n* **Use `'\u003cD/DT\u003e.weekday()'` to get the day of the week (Mon == 0).**\n* **`'fold=1'` means second pass in case of time jumping back for one hour.**\n\n### Now\n```python\n\u003cD/DTn\u003e  = D/DT.today()                     # Current local date or naive datetime.\n\u003cDTn\u003e    = DT.utcnow()                      # Naive datetime from current UTC time.\n\u003cDTa\u003e    = DT.now(\u003ctz\u003e)                     # Aware datetime from current tz time.\n```\n\n### Timezone\n```python\n\u003ctz\u003e     = UTC                              # UTC timezone.\n\u003ctz\u003e     = tzlocal()                        # Local timezone.\n\u003ctz\u003e     = gettz('\u003cCont.\u003e/\u003cCity\u003e')          # Timezone from 'Continent/City_Name' str.\n```\n\n```python\n\u003cDTa\u003e    = \u003cDT\u003e.astimezone(\u003ctz\u003e)            # Datetime, converted to passed timezone.\n\u003cTa/DTa\u003e = \u003cT/DT\u003e.replace(tzinfo=\u003ctz\u003e)      # Unconverted object with new timezone.\n```\n\nRegex\n-----\n```python\nimport re\n\u003cstr\u003e   = re.sub(\u003cregex\u003e, new, text, count=0)  # Substitutes all occurrences.\n\u003clist\u003e  = re.findall(\u003cregex\u003e, text)            # Returns all occurrences.\n\u003clist\u003e  = re.split(\u003cregex\u003e, text, maxsplit=0)  # Use brackets in regex to keep the matches.\n\u003cMatch\u003e = re.search(\u003cregex\u003e, text)             # Searches for first occurrence of pattern.\n\u003cMatch\u003e = re.match(\u003cregex\u003e, text)              # Searches only at the beginning of the text.\n```\n\n\n### Match Object\n```python\n\u003cstr\u003e   = \u003cMatch\u003e.group()   # Whole match.\n\u003cstr\u003e   = \u003cMatch\u003e.group(1)  # Part in first bracket.\n\u003ctuple\u003e = \u003cMatch\u003e.groups()  # All bracketed parts.\n\u003cint\u003e   = \u003cMatch\u003e.start()   # Start index of a match.\n\u003cint\u003e   = \u003cMatch\u003e.end()     # Exclusive end index of a match.\n```\n\n### Special Sequences\n**Expressions below hold true for strings that contain only ASCII characters. Use capital letters for negation.**\n```python\n'\\d' == '[0-9]'          # Digit\n'\\s' == '[ \\t\\n\\r\\f\\v]'  # Whitespace\n'\\w' == '[a-zA-Z0-9_]'   # Alphanumeric\n```\n\n\nCredits\n------\nInspired by: https://github.com/gto76/python-cheatsheet\n","funding_links":[],"categories":["Others"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faneagoie%2Fztm-python-cheat-sheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faneagoie%2Fztm-python-cheat-sheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faneagoie%2Fztm-python-cheat-sheet/lists"}