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