The response has been limited to 50k tokens of the smallest files in the repo. You can remove this limitation by removing the max tokens filter.
└── README.md


/README.md:
--------------------------------------------------------------------------------
   1 | Python ZTM Cheatsheet 💻🚀
   2 | ===============================
   3 | 
   4 | We created this Python 3 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&utm_medium=ztm-python-cheat-sheet)!
   5 | 
   6 | Contents
   7 | --------
   8 | **Python Types:** **[`Numbers`](#numbers)__,__[`Strings`](#strings)__,__[`Boolean`](#boolean)__,__[`Lists`](#lists)__,__[`Dictionaries`](#dictionaries)__,__ [`Tuples`](#tuples)__,__[`Sets`](#sets)__,__[`None`](#none)**  
   9 | 
  10 | **Python Basics:** **[`Comparison Operators`](#comparison-operators)__,__[`Logical Operators`](#logical-operators)__,__[`Loops`](#loops)__,__[`Range`](#range)__,__[`Enumerate`](#enumerate)__,__[`Counter`](#counter)__,__[`Named Tuple`](#named-tuple)__,__[`OrderedDict`](#ordereddict)**    
  11 | 
  12 | **Functions:** **[`Functions`](#functions)__,__[`Lambda`](#lambda)__,__[`Comprehensions`](#comprehensions)__,__[`Map,Filter,Reduce`](#map-filter-reduce)__,__[`Ternary`](#ternary-condition)__,__[`Any,All`](#any-all)__,__[`Closures`](#closures)__,__[`Scope`](#scope)**    
  13 | 
  14 | **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)**  
  15 | 
  16 | 
  17 | Numbers
  18 | ----
  19 | **python's 2 main types for Numbers is int and float (or integers and floating point numbers)**
  20 | ```python
  21 | type(1)   # int 
  22 | type(-10) # int
  23 | type(0)   # int
  24 | type(0.0) # float
  25 | type(2.2) # float
  26 | type(4E2) # float - 4*10 to the power of 2
  27 | ```
  28 | 
  29 | ```python
  30 | # Arithmetic
  31 | 10 + 3  # 13
  32 | 10 - 3  # 7
  33 | 10 * 3  # 30
  34 | 10 ** 3 # 1000
  35 | 10 / 3  # 3.3333333333333335
  36 | 10 // 3 # 3 --> floor division - no decimals and returns an int
  37 | 10 % 3  # 1 --> modulo operator - return the remainder. Good for deciding if number is even or odd
  38 | ```
  39 | 
  40 | ```python
  41 | # Basic Functions
  42 | pow(5, 2)      # 25 --> like doing 5**2
  43 | abs(-50)       # 50
  44 | round(5.46)    # 5
  45 | round(5.468, 2)# 5.47 --> round to nth digit
  46 | bin(512)       # '0b1000000000' -->  binary format
  47 | hex(512)       # '0x200' --> hexadecimal format
  48 | ```
  49 | 
  50 | ```python
  51 | # Converting Strings to Numbers
  52 | age = input("How old are you?")
  53 | age = int(age)
  54 | pi = input("What is the value of pi?")
  55 | pi = float(pi)
  56 | ```
  57 | 
  58 | Strings
  59 | ----
  60 | **strings in python are stored as sequences of letters in memory**
  61 | ```python
  62 | type('Hellloooooo') # str
  63 | 
  64 | 'I\'m thirsty'
  65 | "I'm thirsty"
  66 | "\n" # new line
  67 | "\t" # adds a tab
  68 | 
  69 | 'Hey you!'[4] # y
  70 | name = 'Andrei Neagoie'
  71 | name[4]     # e
  72 | name[:]     # Andrei Neagoie
  73 | name[1:]    # ndrei Neagoie
  74 | name[:1]    # A
  75 | name[-1]    # e
  76 | name[::1]   # Andrei Neagoie
  77 | name[::-1]  # eiogaeN ierdnA
  78 | name[0:10:2]# Ade e
  79 | # : is called slicing and has the format [ start : end : step ]
  80 | 
  81 | 'Hi there ' + 'Timmy' # 'Hi there Timmy' --> This is called string concatenation
  82 | '*'*10 # **********
  83 | ```
  84 | 
  85 | ```python
  86 | # Basic Functions
  87 | len('turtle') # 6
  88 | 
  89 | # Basic Methods
  90 | '  I am alone '.strip()               # 'I am alone' --> Strips all whitespace characters from both ends.
  91 | 'On an island'.strip('d')             # 'On an islan' --> # Strips all passed characters from both ends.
  92 | 'but life is good!'.split()           # ['but', 'life', 'is', 'good!']
  93 | 'Help me'.replace('me', 'you')        # 'Help you' --> Replaces first with second param
  94 | 'Need to make fire'.startswith('Need')# True
  95 | 'and cook rice'.endswith('rice')      # True
  96 | 'still there?'.upper()                # STILL THERE?
  97 | 'HELLO?!'.lower()                     # hello?!
  98 | 'ok, I am done.'.capitalize()         # 'Ok, I am done.'
  99 | 'oh hi there'.count('e')              # 2
 100 | 'bye bye'.index('e')                  # 2
 101 | 'oh hi there'.find('i')               # 4 --> returns the starting index position of the first occurrence
 102 | 'oh hi there'.find('a')               # -1
 103 | 'oh hi there'.index('a')              # Raises ValueError
 104 | ```
 105 | 
 106 | ```python
 107 | # String Formatting
 108 | name1 = 'Andrei'
 109 | name2 = 'Sunny'
 110 | print(f'Hello there {name1} and {name2}')       # Hello there Andrei and Sunny - Newer way to do things as of python 3.6
 111 | print('Hello there {} and {}'.format(name1, name2))# Hello there Andrei and Sunny
 112 | print('Hello there %s and %s' %(name1, name2))  # Hello there Andrei and Sunny --> you can also use %d, %f, %r for integers, floats, string representations of objects respectively
 113 | ```
 114 | 
 115 | ```python
 116 | # Palindrome check
 117 | word = 'reviver'
 118 | p = bool(word.find(word[::-1]) + 1)
 119 | print(p) # True
 120 | ```
 121 | 
 122 | Boolean
 123 | ----
 124 | **True or False. Used in a lot of comparison and logical operations in Python**
 125 | ```python
 126 | bool(True)
 127 | bool(False)
 128 | 
 129 | # all of the below evaluate to False. Everything else will evaluate to True in Python.
 130 | print(bool(None))
 131 | print(bool(False))
 132 | print(bool(0))
 133 | print(bool(0.0))
 134 | print(bool([]))
 135 | print(bool({}))
 136 | print(bool(()))
 137 | print(bool(''))
 138 | print(bool(range(0)))
 139 | print(bool(set()))
 140 | 
 141 | # See Logical Operators and Comparison Operators section for more on booleans.
 142 | ```
 143 | 
 144 | Lists
 145 | ----
 146 | **Unlike strings, lists are mutable sequences in python**
 147 | ```python
 148 | my_list = [1, 2, '3', True]# We assume this list won't mutate for each example below
 149 | len(my_list)               # 4
 150 | my_list.index('3')         # 2
 151 | my_list.count(2)           # 1 --> count how many times 2 appears
 152 | 
 153 | my_list[3]                 # True
 154 | my_list[1:]                # [2, '3', True]
 155 | my_list[:1]                # [1]
 156 | my_list[-1]                # True
 157 | my_list[::1]               # [1, 2, '3', True]
 158 | my_list[::-1]              # [True, '3', 2, 1]
 159 | my_list[0:3:2]             # [1, '3']
 160 | 
 161 | # : is called slicing and has the format [ start : end : step ]
 162 | ```
 163 | 
 164 | ```python
 165 | # Add to List
 166 | my_list * 2                # [1, 2, '3', True, 1, 2, '3', True]
 167 | my_list + [100]            # [1, 2, '3', True, 100] --> doesn't mutate original list, creates new one
 168 | my_list.append(100)        # None --> Mutates original list to [1, 2, '3', True, 100]          # Or: <list> += [<el>]
 169 | my_list.extend([100, 200]) # None --> Mutates original list to [1, 2, '3', True, 100, 200]
 170 | my_list.insert(2, '!!!')   # None -->  [1, 2, '!!!', '3', True] - Inserts item at index and moves the rest to the right.
 171 | 
 172 | ' '.join(['Hello','There'])# 'Hello There' --> Joins elements using string as separator.
 173 | ```
 174 | 
 175 | ```python
 176 | # Copy a List
 177 | basket = ['apples', 'pears', 'oranges']
 178 | new_basket = basket.copy()
 179 | new_basket2 = basket[:]
 180 | ```
 181 | ```python
 182 | # Remove from List
 183 | [1,2,3].pop()    # 3 --> mutates original list, default index in the pop method is -1 (the last item)
 184 | [1,2,3].pop(1)   # 2 --> mutates original list
 185 | [1,2,3].remove(2)# None --> [1,3] Removes first occurrence of item or raises ValueError.
 186 | [1,2,3].clear()  # None --> mutates original list and removes all items: []
 187 | del [1,2,3][0]   # None --> removes item on index 0 or raises IndexError
 188 | ```
 189 | 
 190 | ```python
 191 | # Ordering
 192 | [1,2,5,3].sort()         # None --> Mutates list to [1, 2, 3, 5]
 193 | [1,2,5,3].sort(reverse=True) # None --> Mutates list to [5, 3, 2, 1]
 194 | [1,2,5,3].reverse()      # None --> Mutates list to [3, 5, 2, 1]
 195 | sorted([1,2,5,3])        # [1, 2, 3, 5] --> new list created
 196 | my_list = [(4,1),(2,4),(2,5),(1,6),(8,9)]
 197 | sorted(my_list,key=lambda x: int(x[0])) # [(1, 6), (2, 4), (2, 5), (4, 1), (8, 9)] --> sort the list by 1st (0th index) value of the tuple
 198 | list(reversed([1,2,5,3]))# [3, 5, 2, 1] --> reversed() returns an iterator
 199 | ```
 200 | 
 201 | ```python
 202 | # Useful operations
 203 | 1 in [1,2,5,3]  # True
 204 | min([1,2,3,4,5])# 1
 205 | max([1,2,3,4,5])# 5
 206 | sum([1,2,3,4,5])# 15
 207 | ```
 208 | 
 209 | ```python
 210 | # Get First and Last element of a list
 211 | mList = [63, 21, 30, 14, 35, 26, 77, 18, 49, 10]
 212 | first, *x, last = mList
 213 | print(first) #63
 214 | print(last) #10
 215 | ```
 216 | 
 217 | ```python
 218 | # Matrix
 219 | matrix = [[1,2,3], [4,5,6], [7,8,9]]
 220 | matrix[2][0] # 7 --> Grab first first of the third item in the matrix object
 221 | 
 222 | # Looping through a matrix by rows:
 223 | mx = [[1,2,3],[4,5,6]]
 224 | for row in range(len(mx)):
 225 | 	for col in range(len(mx[0])):
 226 | 		print(mx[row][col]) # 1 2 3 4 5 6
 227 |     
 228 | # Transform into a list:
 229 | [mx[row][col] for row in range(len(mx)) for col in range(len(mx[0]))] # [1,2,3,4,5,6]
 230 | 
 231 | # Combine columns with zip and *:
 232 | [x for x in zip(*mx)] # [(1, 3), (2, 4)]
 233 | 
 234 | ```
 235 | 
 236 | ```python
 237 | # List Comprehensions
 238 | # new_list[<action> for <item> in <iterator> if <some condition>]
 239 | a = [i for i in 'hello']                  # ['h', 'e', 'l', 'l', '0']
 240 | b = [i*2 for i in [1,2,3]]                # [2, 4, 6]
 241 | c = [i for i in range(0,10) if i % 2 == 0]# [0, 2, 4, 6, 8]
 242 | ```
 243 | 
 244 | ```python
 245 | # Advanced Functions
 246 | list_of_chars = list('Helloooo')                                   # ['H', 'e', 'l', 'l', 'o', 'o', 'o', 'o']
 247 | sum_of_elements = sum([1,2,3,4,5])                                 # 15
 248 | element_sum = [sum(pair) for pair in zip([1,2,3],[4,5,6])]         # [5, 7, 9]
 249 | sorted_by_second = sorted(['hi','you','man'], key=lambda el: el[1])# ['man', 'hi', 'you']
 250 | sorted_by_key = sorted([
 251 |                        {'name': 'Bina', 'age': 30},
 252 |                        {'name':'Andy', 'age': 18},
 253 |                        {'name': 'Zoey', 'age': 55}],
 254 |                        key=lambda el: (el['name']))# [{'name': 'Andy', 'age': 18}, {'name': 'Bina', 'age': 30}, {'name': 'Zoey', 'age': 55}]
 255 | ```
 256 | 
 257 | ```python
 258 | # Read line of a file into a list
 259 | with open("myfile.txt") as f:
 260 |   lines = [line.strip() for line in f]
 261 | ```
 262 | 
 263 | Dictionaries
 264 | ----------
 265 | **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**
 266 | ```python
 267 | my_dict = {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False}
 268 | my_dict['name']                      # Andrei Neagoie
 269 | len(my_dict)                         # 3
 270 | list(my_dict.keys())                 # ['name', 'age', 'magic_power']
 271 | list(my_dict.values())               # ['Andrei Neagoie', 30, False]
 272 | list(my_dict.items())                # [('name', 'Andrei Neagoie'), ('age', 30), ('magic_power', False)]
 273 | my_dict['favourite_snack'] = 'Grapes'# {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes'}
 274 | my_dict.get('age')                   # 30 --> Returns None if key does not exist.
 275 | my_dict.get('ages', 0 )              # 0 --> Returns default (2nd param) if key is not found
 276 | 
 277 | #Remove key
 278 | del my_dict['name']
 279 | my_dict.pop('name', None)
 280 | ```
 281 | 
 282 | ```python
 283 | my_dict.update({'cool': True})                                         # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}
 284 | {**my_dict, **{'cool': True} }                                         # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}
 285 | new_dict = dict([['name','Andrei'],['age',32],['magic_power',False]])  # Creates a dict from collection of key-value pairs.
 286 | new_dict = dict(zip(['name','age','magic_power'],['Andrei',32, False]))# Creates a dict from two collections.
 287 | new_dict = my_dict.pop('favourite_snack')                              # Removes item from dictionary.
 288 | ```
 289 | 
 290 | ```python
 291 | # Dictionary Comprehension
 292 | {key: value for key, value in new_dict.items() if key == 'age' or key == 'name'} # {'name': 'Andrei', 'age': 32} --> Filter dict by keys
 293 | ```
 294 | 
 295 | Tuples
 296 | ----
 297 | **Like lists, but they are used for immutable thing (that don't change)**
 298 | ```python
 299 | my_tuple = ('apple','grapes','mango', 'grapes')
 300 | apple, grapes, mango, grapes = my_tuple# Tuple unpacking
 301 | len(my_tuple)                          # 4
 302 | my_tuple[2]                            # mango
 303 | my_tuple[-1]                           # 'grapes'
 304 | ```
 305 | 
 306 | ```python
 307 | # Immutability
 308 | my_tuple[1] = 'donuts'  # TypeError
 309 | my_tuple.append('candy')# AttributeError
 310 | ```
 311 | 
 312 | ```python
 313 | # Methods
 314 | my_tuple.index('grapes') # 1
 315 | my_tuple.count('grapes') # 2
 316 | ```
 317 | 
 318 | ```python
 319 | # Zip
 320 | list(zip([1,2,3], [4,5,6])) # [(1, 4), (2, 5), (3, 6)]
 321 | ```
 322 | 
 323 | ```python
 324 | # unzip
 325 | z = [(1, 2), (3, 4), (5, 6), (7, 8)] # Some output of zip() function
 326 | unzip = lambda z: list(zip(*z))
 327 | unzip(z)
 328 | ```
 329 | 
 330 | Sets
 331 | ---
 332 | **Unorderd collection of unique elements.**
 333 | ```python
 334 | my_set = set()
 335 | my_set.add(1)  # {1}
 336 | my_set.add(100)# {1, 100}
 337 | my_set.add(100)# {1, 100} --> no duplicates!
 338 | ```
 339 | 
 340 | ```python
 341 | new_list = [1,2,3,3,3,4,4,5,6,1]
 342 | set(new_list)           # {1, 2, 3, 4, 5, 6}
 343 | 
 344 | my_set.remove(100)      # {1} --> Raises KeyError if element not found
 345 | my_set.discard(100)     # {1} --> Doesn't raise an error if element not found
 346 | my_set.clear()          # {}
 347 | new_set = {1,2,3}.copy()# {1,2,3}
 348 | ```
 349 | 
 350 | ```python
 351 | set1 = {1,2,3}
 352 | set2 = {3,4,5}
 353 | set3 = set1.union(set2)               # {1,2,3,4,5}
 354 | set4 = set1.intersection(set2)        # {3}
 355 | set5 = set1.difference(set2)          # {1, 2}
 356 | set6 = set1.symmetric_difference(set2)# {1, 2, 4, 5}
 357 | set1.issubset(set2)                   # False
 358 | set1.issuperset(set2)                 # False
 359 | set1.isdisjoint(set2)                 # False --> return True if two sets have a null intersection.
 360 | 
 361 | ```
 362 | 
 363 | ```python
 364 | # Frozenset
 365 | # hashable --> it can be used as a key in a dictionary or as an element in a set.
 366 | <frozenset> = frozenset(<collection>)
 367 | ```
 368 | 
 369 | None
 370 | ----
 371 | **None is used for absence of a value and can be used to show nothing has been assigned to an object**
 372 | ```python
 373 | type(None) # NoneType
 374 | a = None
 375 | ```
 376 | 
 377 | Comparison Operators
 378 | --------
 379 | ```python
 380 | ==                   # equal values
 381 | !=                   # not equal
 382 | >                    # left operand is greater than right operand
 383 | <                    # left operand is less than right operand
 384 | >=                   # left operand is greater than or equal to right operand
 385 | <=                   # left operand is less than or equal to right operand
 386 | <element> is <element> # check if two operands refer to same object in memory
 387 | ```
 388 | 
 389 | Logical Operators
 390 | --------
 391 | ```python
 392 | 1 < 2 and 4 > 1 # True
 393 | 1 > 3 or 4 > 1  # True
 394 | 1 is not 4      # True
 395 | not True        # False
 396 | 1 not in [2,3,4]# True
 397 | 
 398 | if <condition that evaluates to boolean>:
 399 |   # perform action1
 400 | elif <condition that evaluates to boolean>:
 401 |   # perform action2
 402 | else:
 403 |   # perform action3
 404 | ```
 405 | 
 406 | Loops
 407 | --------
 408 | ```python
 409 | my_list = [1,2,3]
 410 | my_tuple = (1,2,3)
 411 | my_list2 = [(1,2), (3,4), (5,6)]
 412 | my_dict = {'a': 1, 'b': 2. 'c': 3}
 413 | 
 414 | for num in my_list:
 415 |     print(num) # 1, 2, 3
 416 | 
 417 | for num in my_tuple:
 418 |     print(num) # 1, 2, 3
 419 | 
 420 | for num in my_list2:
 421 |     print(num) # (1,2), (3,4), (5,6)
 422 | 
 423 | for num in '123':
 424 |     print(num) # 1, 2, 3
 425 | 
 426 | for idx,value in enumerate(my_list):
 427 |     print(idx) # get the index of the item
 428 |     print(value) # get the value
 429 | 
 430 | for k,v in my_dict.items(): # Dictionary Unpacking
 431 |     print(k) # 'a', 'b', 'c'
 432 |     print(v) # 1, 2, 3
 433 | 
 434 | while <condition that evaluates to boolean>:
 435 |   # action
 436 |   if <condition that evaluates to boolean>:
 437 |     break # break out of while loop
 438 |   if <condition that evaluates to boolean>:
 439 |     continue # continue to the next line in the block
 440 | ```
 441 | 
 442 | ```python
 443 | # waiting until user quits
 444 | msg = ''
 445 | while msg != 'quit':
 446 |     msg = input("What should I do?")
 447 |     print(msg)
 448 | ```
 449 | 
 450 | Range
 451 | -----
 452 | ```python
 453 | range(10)          # range(0, 10) --> 0 to 9
 454 | range(1,10)        # range(1, 10)
 455 | list(range(0,10,2))# [0, 2, 4, 6, 8]
 456 | ```
 457 | 
 458 | Enumerate
 459 | ---------
 460 | ```python
 461 | for i, el in enumerate('helloo'):
 462 |   print(f'{i}, {el}')
 463 | # 0, h
 464 | # 1, e
 465 | # 2, l
 466 | # 3, l
 467 | # 4, o
 468 | # 5, o
 469 | ```
 470 | 
 471 | Counter
 472 | -----
 473 | ```python
 474 | from collections import Counter
 475 | colors = ['red', 'blue', 'yellow', 'blue', 'red', 'blue']
 476 | counter = Counter(colors)# Counter({'blue': 3, 'red': 2, 'yellow': 1})
 477 | counter.most_common()[0] # ('blue', 3)
 478 | ```
 479 | 
 480 | Named Tuple
 481 | -----------
 482 | * **Tuple is an immutable and hashable list.**
 483 | * **Named tuple is its subclass with named elements.**
 484 | 
 485 | ```python
 486 | from collections import namedtuple
 487 | Point = namedtuple('Point', 'x y')
 488 | p = Point(1, y=2)# Point(x=1, y=2)
 489 | p[0]             # 1
 490 | p.x              # 1
 491 | getattr(p, 'y')  # 2
 492 | p._fields        # Or: Point._fields #('x', 'y')
 493 | ```
 494 | 
 495 | ```python
 496 | from collections import namedtuple
 497 | Person = namedtuple('Person', 'name height')
 498 | person = Person('Jean-Luc', 187)
 499 | f'{person.height}'           # '187'
 500 | '{p.height}'.format(p=person)# '187'
 501 | ```
 502 | 
 503 | OrderedDict
 504 | --------
 505 | * **Maintains order of insertion**
 506 | ```python
 507 | from collections import OrderedDict
 508 | # Store each person's languages, keeping # track of who responded first. 
 509 | programmers = OrderedDict()
 510 | programmers['Tim'] = ['python', 'javascript']
 511 | programmers['Sarah'] = ['C++']
 512 | programmers['Bia'] = ['Ruby', 'Python', 'Go']
 513 | 
 514 | for name, langs in programmers.items():
 515 |     print(name + '-->')
 516 |     for lang in langs:
 517 |       print('\t' + lang)
 518 | 
 519 | ```
 520 | 
 521 | Functions
 522 | -------
 523 | 
 524 | #### \*args and \*\*kwargs
 525 | **Splat (\*) expands a collection into positional arguments, while splatty-splat (\*\*) expands a dictionary into keyword arguments.**
 526 | ```python
 527 | args   = (1, 2)
 528 | kwargs = {'x': 3, 'y': 4, 'z': 5}
 529 | some_func(*args, **kwargs) # same as some_func(1, 2, x=3, y=4, z=5)
 530 | ```
 531 | 
 532 | #### \* Inside Function Definition
 533 | **Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.**
 534 | ```python
 535 | def add(*a):
 536 |     return sum(a)
 537 | 
 538 | add(1, 2, 3) # 6
 539 | ```
 540 | 
 541 | ##### Ordering of parameters:
 542 | ```python
 543 | def f(*args):                  # f(1, 2, 3)
 544 | def f(x, *args):               # f(1, 2, 3)
 545 | def f(*args, z):               # f(1, 2, z=3)
 546 | def f(x, *args, z):            # f(1, 2, z=3)
 547 | 
 548 | def f(**kwargs):               # f(x=1, y=2, z=3)
 549 | def f(x, **kwargs):            # f(x=1, y=2, z=3) | f(1, y=2, z=3)
 550 | 
 551 | def 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)
 552 | def 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)
 553 | def f(*args, y, **kwargs):     # f(x=1, y=2, z=3) | f(1, y=2, z=3)
 554 | def f(x, *args, z, **kwargs):  # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
 555 | ```
 556 | 
 557 | #### Other Uses of \*
 558 | ```python
 559 | [*[1,2,3], *[4]]                # [1, 2, 3, 4]
 560 | {*[1,2,3], *[4]}                # {1, 2, 3, 4}
 561 | (*[1,2,3], *[4])                # (1, 2, 3, 4)
 562 | {**{'a': 1, 'b': 2}, **{'c': 3}}# {'a': 1, 'b': 2, 'c': 3}
 563 | ```
 564 | 
 565 | ```python
 566 | head, *body, tail = [1,2,3,4,5]
 567 | ```
 568 | 
 569 | 
 570 | Lambda
 571 | ------
 572 | ```python
 573 | # lambda: <return_value>
 574 | # lambda <argument1>, <argument2>: <return_value>
 575 | ```
 576 | 
 577 | ```python
 578 | # Factorial
 579 | from functools import reduce
 580 | 
 581 | n = 3
 582 | factorial = reduce(lambda x, y: x*y, range(1, n+1))
 583 | print(factorial) #6
 584 | ```
 585 | 
 586 | ```python
 587 | # Fibonacci
 588 | fib = lambda n : n if n <= 1 else fib(n-1) + fib(n-2)
 589 | result = fib(10)
 590 | print(result) #55
 591 | ```
 592 | 
 593 | Comprehensions
 594 | ------
 595 | ```python
 596 | <list> = [i+1 for i in range(10)]         # [1, 2, ..., 10]
 597 | <set>  = {i for i in range(10) if i > 5}  # {6, 7, 8, 9}
 598 | <iter> = (i+5 for i in range(10))         # (5, 6, ..., 14)
 599 | <dict> = {i: i*2 for i in range(10)}      # {0: 0, 1: 2, ..., 9: 18}
 600 | ```
 601 | 
 602 | ```python
 603 | output = [i+j for i in range(3) for j in range(3)] # [0, 1, 2, 1, 2, 3, 2, 3, 4]
 604 | 
 605 | # Is the same as:
 606 | output = []
 607 | for i in range(3):
 608 |   for j in range(3):
 609 |     output.append(i+j)
 610 | ```
 611 | 
 612 | Ternary Condition
 613 | -------
 614 | ```python
 615 | # <expression_if_true> if <condition> else <expression_if_false>
 616 | 
 617 | [a if a else 'zero' for a in [0, 1, 0, 3]] # ['zero', 1, 'zero', 3]
 618 | ```
 619 | 
 620 | Map Filter Reduce
 621 | ------
 622 | ```python
 623 | from functools import reduce
 624 | list(map(lambda x: x + 1, range(10)))            # [1, 2, 3, 4, 5, 6, 7, 8, 9,10]
 625 | list(filter(lambda x: x > 5, range(10)))         # (6, 7, 8, 9)
 626 | reduce(lambda acc, x: acc + x, range(10))        # 45
 627 | ```
 628 | 
 629 | Any All
 630 | ------
 631 | ```python
 632 | any([False, True, False])# True if at least one item in collection is truthy, False if empty.
 633 | all([True,1,3,True])     # True if all items in collection are true
 634 | ```
 635 | 
 636 | 
 637 | Closures
 638 | -------
 639 | **We have a closure in Python when:**
 640 | * **A nested function references a value of its enclosing function and then**
 641 | * **the enclosing function returns the nested function.**
 642 | 
 643 | ```python
 644 | def get_multiplier(a):
 645 |     def out(b):
 646 |         return a * b
 647 |     return out
 648 | ```
 649 | 
 650 | ```python
 651 | >>> multiply_by_3 = get_multiplier(3)
 652 | >>> multiply_by_3(10)
 653 | 30
 654 | ```
 655 | 
 656 | * **If multiple nested functions within enclosing function reference the same value, that value gets shared.**
 657 | * **To dynamically access function's first free variable use `'<function>.__closure__[0].cell_contents'`.**
 658 | 
 659 | 
 660 | 
 661 | ### Scope
 662 | **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'.**
 663 | 
 664 | ```python
 665 | def get_counter():
 666 |     i = 0
 667 |     def out():
 668 |         nonlocal i
 669 |         i += 1
 670 |         return i
 671 |     return out
 672 | ```
 673 | 
 674 | ```python
 675 | >>> counter = get_counter()
 676 | >>> counter(), counter(), counter()
 677 | (1, 2, 3)
 678 | ```
 679 | 
 680 | Modules
 681 | ----
 682 | ```python
 683 | if __name__ == '__main__': # Runs main() if file wasn't imported.
 684 |     main()
 685 | ```
 686 | 
 687 | ```python
 688 | import <module_name>
 689 | from <module_name> import <function_name>
 690 | import <module_name> as m
 691 | from <module_name> import <function_name> as m_function
 692 | from <module_name> import *
 693 | ```
 694 | 
 695 | 
 696 | Iterators
 697 | --------
 698 | **In this cheatsheet `'<collection>'` can also mean an iterator.**
 699 | 
 700 | ```python
 701 | <iter> = iter(<collection>)
 702 | <iter> = iter(<function>, to_exclusive)     # Sequence of return values until 'to_exclusive'.
 703 | <el>   = next(<iter> [, default])           # Raises StopIteration or returns 'default' on end.
 704 | ```
 705 | 
 706 | 
 707 | Generators
 708 | ---------
 709 | **Convenient way to implement the iterator protocol.**
 710 | 
 711 | ```python
 712 | def count(start, step):
 713 |     while True:
 714 |         yield start
 715 |         start += step
 716 | ```
 717 | 
 718 | ```python
 719 | >>> counter = count(10, 2)
 720 | >>> next(counter), next(counter), next(counter)
 721 | (10, 12, 14)
 722 | ```
 723 | 
 724 | 
 725 | Decorators
 726 | ---------
 727 | **A decorator takes a function, adds some functionality and returns it.**
 728 | 
 729 | ```python
 730 | @decorator_name
 731 | def function_that_gets_passed_to_decorator():
 732 |     ...
 733 | ```
 734 | 
 735 | **Example Decorator: timing performance using a decorator.**
 736 | * **The functools decorator `@functools.wraps` is used to maintain function naming and 
 737 | documentation of the function within the decorator.**
 738 | 
 739 | ```python
 740 | from time import time 
 741 | import functools
 742 | 
 743 | def performance(func):
 744 | 
 745 |     @functools.wraps()
 746 |     def wrapper(*args, **kwargs):
 747 |         t1 = time()
 748 |         result = func(*args, **kwargs)
 749 |         t2 = time() 
 750 |         print(f"Took: {t2 - t1} ms")
 751 |         return result
 752 |     return wrapper
 753 | 
 754 | # calling a function with the decorator 
 755 | @performance
 756 | def long_time():
 757 |     print(sum(i*i for i in range(10000)))
 758 | ``` 
 759 | 
 760 | ### Debugger Example
 761 | **Decorator that prints function's name every time it gets called.**
 762 | 
 763 | ```python
 764 | from functools import wraps
 765 | 
 766 | def debug(func):
 767 |     @wraps(func)
 768 |     def out(*args, **kwargs):
 769 |         print(func.__name__)
 770 |         return func(*args, **kwargs)
 771 |     return out
 772 | 
 773 | @debug
 774 | def add(x, y):
 775 |     return x + y
 776 | ```
 777 | * **Wraps is a helper decorator that copies metadata of function add() to function out().**
 778 | * **Without it `'add.__name__'` would return `'out'`.**
 779 | 
 780 | 
 781 | 
 782 | Class
 783 | -----
 784 | **User defined objects are created using the class keyword**
 785 | 
 786 | ```python
 787 | class <name>:
 788 |     age = 80 # Class Object Attribute
 789 |     def __init__(self, a):
 790 |         self.a = a # Object Attribute
 791 | 
 792 |     @classmethod
 793 |     def get_class_name(cls):
 794 |         return cls.__name__
 795 | ```
 796 | 
 797 | ### Inheritance
 798 | ```python
 799 | class Person:
 800 |     def __init__(self, name, age):
 801 |         self.name = name
 802 |         self.age  = age
 803 | 
 804 | class Employee(Person):
 805 |     def __init__(self, name, age, staff_num):
 806 |         super().__init__(name, age)
 807 |         self.staff_num = staff_num
 808 | ```
 809 | 
 810 | ### Multiple Inheritance
 811 | ```python
 812 | class A: pass
 813 | class B: pass
 814 | class C(A, B): pass
 815 | ```
 816 | 
 817 | **MRO determines the order in which parent classes are traversed when searching for a method:**
 818 | ```python
 819 | >>> C.mro()
 820 | [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
 821 | ```
 822 | 
 823 | Exceptions
 824 | ----------
 825 | 
 826 | ```python
 827 | try:
 828 |   5/0
 829 | except ZeroDivisionError:
 830 |   print("No division by zero!")
 831 | ```
 832 | 
 833 | ```python
 834 | while True:
 835 |   try:
 836 |     x = int(input('Enter your age: '))
 837 |   except ValueError:
 838 |     print('Oops!  That was no valid number.  Try again...')
 839 |   else: # code that depends on the try block running successfully should be placed in the else block.
 840 |     print('Carry on!')
 841 |     break
 842 | ```
 843 | 
 844 | ### Raising Exception
 845 | ```python
 846 | raise ValueError('some error message')
 847 | ```
 848 | 
 849 | ### Finally
 850 | ```python
 851 | try:
 852 |   raise KeyboardInterrupt
 853 | except:
 854 |   print('oops')
 855 | finally:
 856 |   print('All done!')
 857 | 
 858 | ```
 859 | 
 860 | 
 861 | 
 862 | Command Line Arguments
 863 | ----------------------
 864 | ```python
 865 | import sys
 866 | script_name = sys.argv[0]
 867 | arguments   = sys.argv[1:]
 868 | ```
 869 | 
 870 | File IO
 871 | ----
 872 | **Opens a file and returns a corresponding file object.**
 873 | 
 874 | ```python
 875 | <file> = open('<path>', mode='r', encoding=None)
 876 | ```
 877 | 
 878 | ### Modes
 879 | * **`'r'`  - Read (default).**
 880 | * **`'w'`  - Write (truncate).**
 881 | * **`'x'`  - Write or fail if the file already exists.**
 882 | * **`'a'`  - Append.**
 883 | * **`'w+'` - Read and write (truncate).**
 884 | * **`'r+'` - Read and write from the start.**
 885 | * **`'a+'` - Read and write from the end.**
 886 | * **`'t'`  - Text mode (default).**
 887 | * **`'b'`  - Binary mode.**
 888 | 
 889 | ### File
 890 | ```python
 891 | <file>.seek(0)                      # Moves to the start of the file.
 892 | ```
 893 | 
 894 | ```python
 895 | <str/bytes> = <file>.readline()     # Returns a line.
 896 | <list>      = <file>.readlines()    # Returns a list of lines.
 897 | ```
 898 | 
 899 | ```python
 900 | <file>.write(<str/bytes>)           # Writes a string or bytes object.
 901 | <file>.writelines(<list>)           # Writes a list of strings or bytes objects.
 902 | ```
 903 | * **Methods do not add or strip trailing newlines.**
 904 | 
 905 | ### Read Text from File
 906 | ```python
 907 | def read_file(filename):
 908 |     with open(filename, encoding='utf-8') as file:
 909 |         return file.readlines() # or read()
 910 | 
 911 | for line in read_file(filename):
 912 |   print(line)
 913 | ```
 914 | 
 915 | ### Write Text to File
 916 | ```python
 917 | def write_to_file(filename, text):
 918 |     with open(filename, 'w', encoding='utf-8') as file:
 919 |         file.write(text)
 920 | ```
 921 | 
 922 | ### Append Text to File
 923 | ```python
 924 | def append_to_file(filename, text):
 925 |     with open(filename, 'a', encoding='utf-8') as file:
 926 |         file.write(text)
 927 | ```
 928 | 
 929 | Useful Libraries
 930 | =========
 931 | 
 932 | CSV
 933 | ---
 934 | ```python
 935 | import csv
 936 | ```
 937 | 
 938 | ### Read Rows from CSV File
 939 | ```python
 940 | def read_csv_file(filename):
 941 |     with open(filename, encoding='utf-8') as file:
 942 |         return csv.reader(file, delimiter=';')
 943 | ```
 944 | 
 945 | ### Write Rows to CSV File
 946 | ```python
 947 | def write_to_csv_file(filename, rows):
 948 |     with open(filename, 'w', encoding='utf-8') as file:
 949 |         writer = csv.writer(file, delimiter=';')
 950 |         writer.writerows(rows)
 951 | ```
 952 | 
 953 | 
 954 | JSON
 955 | ----
 956 | ```python
 957 | import json
 958 | <str>    = json.dumps(<object>, ensure_ascii=True, indent=None)
 959 | <object> = json.loads(<str>)
 960 | ```
 961 | 
 962 | ### Read Object from JSON File
 963 | ```python
 964 | def read_json_file(filename):
 965 |     with open(filename, encoding='utf-8') as file:
 966 |         return json.load(file)
 967 | ```
 968 | 
 969 | ### Write Object to JSON File
 970 | ```python
 971 | def write_to_json_file(filename, an_object):
 972 |     with open(filename, 'w', encoding='utf-8') as file:
 973 |         json.dump(an_object, file, ensure_ascii=False, indent=2)
 974 | ```
 975 | 
 976 | 
 977 | Pickle
 978 | ------
 979 | ```python
 980 | import pickle
 981 | <bytes>  = pickle.dumps(<object>)
 982 | <object> = pickle.loads(<bytes>)
 983 | ```
 984 | 
 985 | ### Read Object from File
 986 | ```python
 987 | def read_pickle_file(filename):
 988 |     with open(filename, 'rb') as file:
 989 |         return pickle.load(file)
 990 | ```
 991 | 
 992 | ### Write Object to File
 993 | ```python
 994 | def write_to_pickle_file(filename, an_object):
 995 |     with open(filename, 'wb') as file:
 996 |         pickle.dump(an_object, file)
 997 | ```
 998 | 
 999 | 
1000 | Profile
1001 | -------
1002 | ### Basic
1003 | ```python
1004 | from time import time
1005 | start_time = time()  # Seconds since
1006 | ...
1007 | duration = time() - start_time
1008 | ```
1009 | 
1010 | ### Math
1011 | ```python
1012 | from math import e, pi
1013 | from math import cos, acos, sin, asin, tan, atan, degrees, radians
1014 | from math import log, log10, log2
1015 | from math import inf, nan, isinf, isnan
1016 | ```
1017 | 
1018 | ### Statistics
1019 | ```python
1020 | from statistics import mean, median, variance, pvariance, pstdev
1021 | ```
1022 | 
1023 | ### Random
1024 | ```python
1025 | from random import random, randint, choice, shuffle
1026 | random() # random float between 0 and 1
1027 | randint(0, 100) # random integer between 0 and 100
1028 | random_el = choice([1,2,3,4]) # select a random element from list
1029 | shuffle([1,2,3,4]) # shuffles a list
1030 | ```
1031 | 
1032 | 
1033 | Datetime
1034 | --------
1035 | * **Module 'datetime' provides 'date' `<D>`, 'time' `<T>`, 'datetime' `<DT>` and 'timedelta' `<TD>` classes. All are immutable and hashable.**
1036 | * **Time and datetime can be 'aware' `<a>`, meaning they have defined timezone, or 'naive' `<n>`, meaning they don't.**
1037 | * **If object is naive it is presumed to be in system's timezone.**
1038 | 
1039 | ```python
1040 | from datetime import date, time, datetime, timedelta
1041 | from dateutil.tz import UTC, tzlocal, gettz
1042 | ```
1043 | 
1044 | ### Constructors
1045 | ```python
1046 | <D>  = date(year, month, day)
1047 | <T>  = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
1048 | <DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
1049 | <TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
1050 |                  minutes=0, hours=0, weeks=0)
1051 | ```
1052 | * **Use `'<D/DT>.weekday()'` to get the day of the week (Mon == 0).**
1053 | * **`'fold=1'` means second pass in case of time jumping back for one hour.**
1054 | 
1055 | ### Now
1056 | ```python
1057 | <D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
1058 | <DTn>    = DT.utcnow()                      # Naive datetime from current UTC time.
1059 | <DTa>    = DT.now(<tz>)                     # Aware datetime from current tz time.
1060 | ```
1061 | 
1062 | ### Timezone
1063 | ```python
1064 | <tz>     = UTC                              # UTC timezone.
1065 | <tz>     = tzlocal()                        # Local timezone.
1066 | <tz>     = gettz('<Cont.>/<City>')          # Timezone from 'Continent/City_Name' str.
1067 | ```
1068 | 
1069 | ```python
1070 | <DTa>    = <DT>.astimezone(<tz>)            # Datetime, converted to passed timezone.
1071 | <Ta/DTa> = <T/DT>.replace(tzinfo=<tz>)      # Unconverted object with new timezone.
1072 | ```
1073 | 
1074 | Regex
1075 | -----
1076 | ```python
1077 | import re
1078 | <str>   = re.sub(<regex>, new, text, count=0)  # Substitutes all occurrences.
1079 | <list>  = re.findall(<regex>, text)            # Returns all occurrences.
1080 | <list>  = re.split(<regex>, text, maxsplit=0)  # Use brackets in regex to keep the matches.
1081 | <Match> = re.search(<regex>, text)             # Searches for first occurrence of pattern.
1082 | <Match> = re.match(<regex>, text)              # Searches only at the beginning of the text.
1083 | ```
1084 | 
1085 | 
1086 | ### Match Object
1087 | ```python
1088 | <str>   = <Match>.group()   # Whole match.
1089 | <str>   = <Match>.group(1)  # Part in first bracket.
1090 | <tuple> = <Match>.groups()  # All bracketed parts.
1091 | <int>   = <Match>.start()   # Start index of a match.
1092 | <int>   = <Match>.end()     # Exclusive end index of a match.
1093 | ```
1094 | 
1095 | ### Special Sequences
1096 | **Expressions below hold true for strings that contain only ASCII characters. Use capital letters for negation.**
1097 | ```python
1098 | '\d' == '[0-9]'          # Digit
1099 | '\s' == '[ \t\n\r\f\v]'  # Whitespace
1100 | '\w' == '[a-zA-Z0-9_]'   # Alphanumeric
1101 | ```
1102 | 
1103 | 
1104 | Credits
1105 | ------
1106 | Inspired by: https://github.com/gto76/python-cheatsheet
1107 | 


--------------------------------------------------------------------------------