{"id":21489529,"url":"https://github.com/s44wn/python-cheatsheet","last_synced_at":"2026-01-02T23:58:44.970Z","repository":{"id":164794549,"uuid":"544765511","full_name":"S44WN/python-cheatsheet","owner":"S44WN","description":"summarizes all the python stuff","archived":false,"fork":false,"pushed_at":"2022-10-03T13:31:20.000Z","size":12,"stargazers_count":5,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-23T20:22:39.857Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/S44WN.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":"2022-10-03T07:24:24.000Z","updated_at":"2022-10-05T14:14:08.000Z","dependencies_parsed_at":null,"dependency_job_id":"c2ebdc92-8b79-405f-b2f3-fc37ff632a51","html_url":"https://github.com/S44WN/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/S44WN%2Fpython-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/S44WN%2Fpython-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/S44WN%2Fpython-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/S44WN%2Fpython-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/S44WN","download_url":"https://codeload.github.com/S44WN/python-cheatsheet/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244020844,"owners_count":20385023,"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":[],"created_at":"2024-11-23T14:21:27.627Z","updated_at":"2026-01-02T23:58:44.932Z","avatar_url":"https://github.com/S44WN.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# \u003ccenter\u003e 🐍 Python3 Cheatsheet 💻 \u003c/center\u003e\n\nThis a summary of all the things we use in python. This can be a great help or reference for students who just started or a reference for seasoned coders.\n\u003cbr\u003e\n\n## Contents\n\n#### ( click on links to skip to that topic )\n\n\u003cbr\u003e\n\n### **Python Data Types:**\n\n- [`Numbers`](#numbers)\n- [`Strings`](#strings)\n- [`Boolean`](#boolean)\n- [`Lists`](#lists)\n- [`Dictionaries`](#dictionaries)\n- [`Tuples`](#tuples)\n- [`Sets`](#sets)\n- [`None`](#none)\n\n\u003cbr\u003e\n\n### **Python Basics:**\n\n- [`Comparison Operators`](#comparison-operators)\n- [`Logical Operators`](#logical-operators)\n- [`Loops`](#loops)\n- [`Range`](#range)\n- [`Enumerate`](#enumerate)\n- [`Counter`](#counter)\n- [`Named Tuple`](#named-tuple)\n- [`OrderedDict`](#ordereddict)\n\n\u003cbr\u003e\n\n### **Functions:**\n\n- [`Functions`](#functions)\n- [`Lambda Function`](#lambda)\n- [`Comprehensions`](#comprehensions)\n- [`Map,Filter,Reduce`](#map-filter-reduce)\n- [`Ternary`](#ternary-condition)\n- [`Any,All`](#any-all)\n- [`Closures`](#closures)\n- [`Scope`](#scope)\n\n\u003cbr\u003e\n\n### **Advanced Python:**\n\n- [`Modules`](#modules)\n- [`Iterators`](#iterators)\n- [`Generators`](#generators)\n- [`Decorators`](#decorators)\n- [`Class`](#class)\n- [`Exceptions`](#exceptions)\n- [`Command Line Arguments`](#command-line-arguments)\n- [`File IO`](#file-io)\n- [`Useful Libraries`](#useful-libraries)\n\n\u003cbr\u003e\n\n## Numbers\n\nPython has two main types of Numbers - \u003cbr\u003e **int** ( or integers) and \u003cbr\u003e **float** (or floating point numbers) \u003cbr\u003e\n\n```python\n#integers\ntype(1)   # int\ntype(-10) # int\ntype(0)   # int\n\n#floating point numbers (decimal)\ntype(0.0) # float\ntype(2.2) # float\ntype(4E2) # float - 4*10 to the power of 2\n```\n\n```python\n# Arithmetic\n\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 reminder. Good for deciding if number is even or odd\n```\n\n```python\n# Basic Math Functions on int and float\n\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\n\nage = input(\"How old are you?\")\nage = int(age)\n\npi = input(\"What is the value of pi?\")\npi = float(pi)\n```\n\n\u003cbr\u003e\n\n## Strings\n\n**Strings in python are stored as sequences of letters in memory. You can imgine it as a**\n\n```python\ntype('Hellloooooo') # str\n\n#when needed a single quote in a string\n'I\\'m thirsty'\n\"I'm thirsty\"\n\n#escape characters\n\"\\n\" # new line\n\"\\t\" # adds a tab\n\n\n# String slicing\n# index always starts with 0\n# : is called slicing and has the format [ start : end : step ]\n\n'Hey you!'[4] # y\nname = 'Tomorrow Never Dies'\nname[4]     # r\nname[:]     # Tomorrow Never Dies\nname[1:]    # omorrow Never Dies\nname[:1]    # T\nname[-1]    # s\nname[::1]   # Tomorrow Never Dies\nname[::-1]  # seiD reveN worromoT\nname[0:10:2]# Tmro N\n\n\n'Hi there ' + 'S44WN' # 'Hi there S44WN' --\u003e This is called string concatenation\n\n#string multiplies\n'*'*10 # **********\n'hey'*3 #heyheyhey\n\n```\n\n```python\n\n# Basic Functions\nlen('turtle') # 6\n\n# Basic Methods --\n\n'  I am alone '.strip()\n# 'I am alone' --\u003e Strips all whitespace characters from both ends.\n\n'On an island'.strip('d')\n# 'On an islan' --\u003e # Strips all passed characters from both ends.\n\n'but life is good!'.split()\n# ['but', 'life', 'is', 'good!']\n\n'Help me'.replace('me', 'you')\n# 'Help you' --\u003e Replaces first with second param\n\n'Need to make fire'.startswith('Need')# True\n\n'and cook rice'.endswith('rice')      # True\n\n'still there?'.upper()                # STILL THERE?\n\n'HELLO?!'.lower()                     # hello?!\n\n'ok, I am done.'.capitalize()         # 'Ok, I am done.'\n\n'oh hi there'.count('e')              # 2\n\n'bye bye'.index('e')                  # 2\n\n'oh hi there'.find('i')               # 4 --\u003e returns the starting index position of the first occurrence\n\n'oh hi there'.find('a')               # -1\n\n'oh hi there'.index('a')              # Raises ValueError\n\n```\n\n```python\n\n# String Formatting\n\nname1 = 'Steve'\nname2 = 'Peggy'\n\nprint(f'Hello there {name1} and {name2}')       # Hello there Steve and Peggy - Newer way to do things as of python 3.6\n\nprint('Hello there {} and {}'.format(name1, name2))# Hello there Steve and Peggy\n\nprint('Hello there %s and %s' %(name1, name2))  # Hello there Steve and Peggy --\u003e you can also use %d, %f, %r for integers, floats, string representations of objects respectively\n\n```\n\n```python\n# Palindrome check\nword = 'reviver'\np = bool(word.find(word[::-1]) + 1)\nprint(p) # True\n\n```\n\n## Boolean\n\n**True or False. Used in a lot of comparison and logical operations in Python**\n\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\n## Lists\n\n**Unlike strings, lists are mutable sequences in python**\n\n```python\n\nmy_list = [1, 2, '3', True]# We assume this list won't mutate for each example below\n\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\n\nmy_list * 2                # [1, 2, '3', True, 1, 2, '3', True]\n\nmy_list + [100]            # [1, 2, '3', True, 100] --\u003e doesn't mutate original list, creates new one\n\nmy_list.append(100)        # None --\u003e Mutates original list to [1, 2, '3', True, 100]          # Or: \u003clist\u003e += [\u003cel\u003e]\n\nmy_list.extend([100, 200]) # None --\u003e Mutates original list to [1, 2, '3', True, 100, 200]\n\nmy_list.insert(2, '!!!')   # None --\u003e  [1, 2, '!!!', '3', True] - Inserts item at index and moves the rest to the right.\n\n\n' '.join(['Hello','There'])# 'Hello There' --\u003e Joins elements using string as separator.\n```\n\n```python\n# Copy a List\n\nbasket = ['apples', 'pears', 'oranges']\nnew_basket = basket.copy()\nnew_basket2 = basket[:]\n```\n\n```python\n# Remove from List\n\n[1,2,3].pop()    # 3 --\u003e mutates original list, default index in the pop method is -1 (the last item)\n\n[1,2,3].pop(1)   # 2 --\u003e mutates original list\n\n[1,2,3].remove(2)# None --\u003e [1,3] Removes first occurrence of item or raises ValueError.\n\n[1,2,3].clear()  # None --\u003e mutates original list and removes all items: []\n\ndel [1,2,3][0]   # None --\u003e removes item on index 0 or raises IndexError\n\n```\n\n```python\n# Ordering\n\n[1,2,5,3].sort()         # None --\u003e Mutates list to [1, 2, 3, 5]\n\n[1,2,5,3].sort(reverse=True) # None --\u003e Mutates list to [5, 3, 2, 1]\n\n[1,2,5,3].reverse()      # None --\u003e Mutates list to [3, 5, 2, 1]\n\nsorted([1,2,5,3])        # [1, 2, 3, 5] --\u003e new list created\n\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\n\nlist(reversed([1,2,5,3]))# [3, 5, 2, 1] --\u003e reversed() returns an iterator\n\n```\n\n```python\n# Useful operations\n\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\n```python\n# Get First and Last element of a list\n\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\n\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]\n\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\n\nlist_of_chars = list('Helloooo')                                   # ['H', 'e', 'l', 'l', 'o', 'o', 'o', 'o']\n\nsum_of_elements = sum([1,2,3,4,5])                                 # 15\n\nelement_sum = [sum(pair) for pair in zip([1,2,3],[4,5,6])]         # [5, 7, 9]\n\nsorted_by_second = sorted(['hi','you','man'], key=lambda el: el[1])# ['man', 'hi', 'you']\n\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']))\n                       # [{'name': 'Andy', 'age': 18}, {'name': 'Bina', 'age': 30}, {'name': 'Zoey', 'age': 55}]\n\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\n## Dictionaries\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\n```python\nmy_dict = {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False}\n\nmy_dict['name']                      # Andrei Neagoie\n\nlen(my_dict)                         # 3\n\nlist(my_dict.keys())                 # ['name', 'age', 'magic_power']\n\nlist(my_dict.values())               # ['Andrei Neagoie', 30, False]\n\nlist(my_dict.items())                # [('name', 'Andrei Neagoie'), ('age', 30), ('magic_power', False)]\n\nmy_dict['favourite_snack'] = 'Grapes'# {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes'}\n\nmy_dict.get('age')                   # 30 --\u003e Returns None if key does not exist.\n\nmy_dict.get('ages', 0 )              # 0 --\u003e Returns default (2nd param) if key is not found\n\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\n{**my_dict, **{'cool': True} }                                         # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}\n\nnew_dict = dict([['name','Andrei'],['age',32],['magic_power',False]])  # Creates a dict from collection of key-value pairs.\n\nnew_dict = dict(zip(['name','age','magic_power'],['Andrei',32, False]))# Creates a dict from two collections.\n\nnew_dict = my_dict.pop('favourite_snack')                              # Removes item from dictionary.\n\n```\n\n```python\n# Dictionary Comprehension\n\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\n## Tuples\n\n**Like lists, but they are used for immutable thing (that don't change)**\n\n```python\n\nmy_tuple = ('apple','grapes','mango', 'grapes')\n\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\n\nmy_tuple[1] = 'donuts'  # TypeError\nmy_tuple.append('candy')# AttributeError\n```\n\n```python\n# Methods\n\nmy_tuple.index('grapes') # 1\nmy_tuple.count('grapes') # 2\n```\n\n```python\n# Zip\n\nlist(zip([1,2,3], [4,5,6])) # [(1, 4), (2, 5), (3, 6)]\n```\n\n```python\n# unzip\n\nz = [(1, 2), (3, 4), (5, 6), (7, 8)] # Some output of zip() function\n\nunzip = lambda z: list(zip(*z))\nunzip(z)\n```\n\n## Sets\n\n**Unorderd collection of unique elements.**\n\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\n\nmy_set.discard(100)     # {1} --\u003e Doesn't raise an error if element not found\n\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\n## None\n\n**None is used for absence of a value and can be used to show nothing has been assigned to an object**\n\n```python\ntype(None) # NoneType\na = None\n```\n\n## Comparison 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\n## Logical Operators\n\n```python\n\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\n## Loops\n\n```python\n\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\n\nmsg = ''\nwhile msg != 'quit':\n    msg = input(\"What should I do?\")\n    print(msg)\n```\n\n## Range\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\n## Enumerate\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\n## Counter\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\n## Named 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\n## OrderedDict\n\n- **Maintains order of insertion**\n\n```python\nfrom collections import OrderedDict\n# Store each person's languages, keeping # track of who responded first.\n\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\n## Functions\n\n#### \\*args and \\*\\*kwargs\n\n**Splat (\\*) expands a collection into positional arguments, while splatty-splat (\\*\\*) expands a dictionary into keyword arguments.**\n\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\n**Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.**\n\n```python\ndef add(*a):\n    return sum(a)\n\nadd(1, 2, 3) # 6\n```\n\n##### Ordering of parameters:\n\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\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## Lambda\n\n```python\n\n# lambda: \u003creturn_value\u003e\n# lambda \u003cargument1\u003e, \u003cargument2\u003e: \u003creturn_value\u003e\n```\n\n```python\n\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\n\nfib = lambda n : n if n \u003c= 1 else fib(n-1) + fib(n-2)\nresult = fib(10)\nprint(result) #55\n```\n\n## Comprehensions\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\n## Ternary Condition\n\n```python\n\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\n## Map Filter Reduce\n\n```python\n\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\n## Any All\n\n```python\n\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## Closures\n\n**We have a closure in Python when:**\n\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### Scope\n\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\n## Modules\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## Iterators\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## Generators\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## Decorators\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\n- **The functools decorator `@functools.wraps` is used to maintain function naming and\n  documentation 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\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\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## Class\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\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\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\n```python\n\u003e\u003e\u003e C.mro()\n[\u003cclass 'C'\u003e, \u003cclass 'A'\u003e, \u003cclass 'B'\u003e, \u003cclass 'object'\u003e]\n```\n\n## Exceptions\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\n```python\nraise ValueError('some error message')\n```\n\n### Finally\n\n```python\ntry:\n  raise KeyboardInterrupt\nexcept:\n  print('oops')\nfinally:\n  print('All done!')\n\n```\n\n## Command Line Arguments\n\n```python\nimport sys\nscript_name = sys.argv[0]\narguments   = sys.argv[1:]\n```\n\n## File 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\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\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\n- **Methods do not add or strip trailing newlines.**\n\n### Read Text from File\n\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\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\n```python\ndef append_to_file(filename, text):\n    with open(filename, 'a', encoding='utf-8') as file:\n        file.write(text)\n```\n\n# Useful Libraries\n\n## CSV\n\n```python\nimport csv\n```\n\n### Read Rows from CSV File\n\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\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## JSON\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\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\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## Pickle\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\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\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## Profile\n\n### Basic\n\n```python\nfrom time import time\nstart_time = time()  # Seconds since\n...\nduration = time() - start_time\n```\n\n### Math\n\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\n```python\nfrom statistics import mean, median, variance, pvariance, pstdev\n```\n\n### Random\n\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## Datetime\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\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\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\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\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\n## Regex\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### Match Object\n\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\n**Expressions below hold true for strings that contain only ASCII characters. Use capital letters for negation.**\n\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## Credits\n\nInspired by: https://github.com/aneagoie/ztm-python-cheat-sheet\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fs44wn%2Fpython-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fs44wn%2Fpython-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fs44wn%2Fpython-cheatsheet/lists"}