├── LICENSE ├── README.md └── _config.yml /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Nicholas Young 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Table of Contents 2 | - [Built-in Types](#built-in-types) 3 | - [Boolean Types](#boolean-types) 4 | - [Numeric Types](#numeric-types) 5 | - [Sequence Types](#sequence-types) 6 | - [Mutable Sequences](#mutable-sequences) 7 | - [Immutable Sequences](#immutable-sequences) 8 | - [Set Types](#set-types) 9 | - [Mapping Types](#mapping-types) 10 | - [Dictionaries](#dictionaries) 11 | - [Iteration](#dictionary-iteration) 12 | - [Sorting](#dictionary-sorting) 13 | - [Lists](#lists) 14 | - [Comprehensions](#list-comprehensions) 15 | - [Initialization](#list-initialization) 16 | - [Reversal](#list-reversal) 17 | - [Sorting](#list-sorting) 18 | - [Strings](#strings) 19 | - [From List](#from-list) 20 | - [Python String Constants](#string-constants) 21 | - [`isalnum()`](#isalnum) 22 | - [`split()`](#split) 23 | - [`strip()`](#strip) 24 | - [`str()` vs `repr()`](#str-vs-repr) 25 | - [Iterators](#iterators) 26 | - [Iterator vs Iterable](#iterator-vs-iterable) 27 | - [How for loop actually works](#how-for-loop-actually-works) 28 | - [Creating an Iterator](#creating-an-iterator) 29 | - [Functional Iteration](#functional-iteration) 30 | - [`map()`](#map) 31 | - [`filter()`](#filter) 32 | - [`reduce()`](#reduce) 33 | - [Decorators](#decorators) 34 | - [`@classmethod`](#classmethod) 35 | - [`@staticmethod`](#staticmethod) 36 | - [`@property`](#property) 37 | - [Generators](#generators) 38 | - [Using `yield`](#using-yield) 39 | - [Generator Expressions](#generator-expressions) 40 | - [Other Useful Built-in Functions](#other-useful-built-in-functions) 41 | - [`abs()`](#abs) 42 | - [`any()`](#any) 43 | - [`all()`](#all) 44 | - [`chr()`](#chr) 45 | - [`enumerate()`](#enumerate) 46 | - [`input()`](#input) 47 | - [`isinstance()`](#isinstance) 48 | - [`len()`](#len) 49 | - [`max()`](#max) 50 | - [`min()`](#min) 51 | - [`ord()`](#ord) 52 | - [`pow()`](#pow) 53 | - [`type()`](#type) 54 | - [Common Gotchas](#common-gotchas) 55 | - [Nested List Initialization](#nested-list-initialization) 56 | - [Mutable Default Arguments](#mutable-default-arguments) 57 | 58 | [▲ TOP](#table-of-contents) 59 | ## Built-in Types 60 | In this section I have included information on the more basic built-in types. For information on more specialized built-in types, check out the [Python documentation](https://docs.python.org/3/library/stdtypes.html) 61 | 62 | ### Boolean Types 63 | ```python3 64 | class 'bool' 65 | ``` 66 | 67 | By default, an object is considered `True` unless its class defines either a `__bool__()` method that returns `False` or a `__len__()` method that returns zero. Here are most of the built-in objects considered `False`: 68 | - constants defined to be false: `None` and `False` 69 | - zero of any numeric type: `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)` 70 | - empty sequences and collections: `''`, `()`, `[]`, `{}`, `set()`, `range(0)` 71 | 72 | ### Numeric Types 73 | ```python3 74 | class 'int' 75 | class 'float' 76 | class 'complex' 77 | ``` 78 | 79 | Integers have unlimited precision. Floating point numbers are usually implemented using `double` in C, and are therefore system-dependent. Complex numbers have a real and imaginary part, which can be accessed using `z.real` and `z.imag`, respectively. Complex numbers must include `j` appended to a numeric literal (`0j` is acceptable for when you want a `complex` value with no imaginary part). 80 | 81 | The standard libarary includes additional numeric types, [Fraction](https://docs.python.org/3/library/fractions.html#module-fractions)s which hold rationals, and [Decimal](https://docs.python.org/3/library/decimal.html#module-decimal)s which hold floating-point numbers with user-definable precision. 82 | 83 | ### Sequence Types 84 | Immutable sequences have support for the `hash()` built-in, while mutable sequences do not. This means that immutable sequences can be used as `dict` keys or stored in `set` and `frozenset` instances, while mutable sequences cannot. 85 | 86 | #### Mutable Sequences 87 | ```python3 88 | class 'list' 89 | class 'bytearray 90 | ``` 91 | 92 | `bytearray` objects are a mutable counterpart to `bytes` objects. 93 | 94 | #### Immutable Sequences 95 | ```python3 96 | class 'tuple' 97 | class 'range' 98 | class 'str' 99 | class 'bytes' 100 | ``` 101 | 102 | `bytes` objects are sequences of single bytes. The syntax for `bytes` literals is largely the same as that for string literals, except that a `b` prefix is added: 103 | - Single quotes: `b'still allows embedded "double" quotes'` 104 | - Double quotes: `b"still allows embedded 'single' quotes"` 105 | - Triple quotes: `b'''3 single quotes'''`, `b"""3 double quotes"""` 106 | 107 | Only ASCII chars are permitted in `bytes` literals. 108 | `bytes` objects actually behave like immutable sequences of integers, with each value restricted to `0 <= x < 256`. 109 | 110 | `bytes` objects can be created in several ways: 111 | - A zero-filled bytes object of a specific length: `bytes(10)` 112 | - From an iterable of integers: `bytes(range(20))` 113 | - Copying existing binary data via the buffer protocol: `bytes(obj)` 114 | 115 | ### Set Types 116 | ```python3 117 | class 'set' 118 | class 'frozenset' 119 | ``` 120 | 121 | `set` is mutable, while `frozenset` is immutable. 122 | Note that since `frozenset` is immutable, it must be entirely populated at the moment of construction. It cannot use the literal curly brace syntax that ordinary `set` uses, as that syntax is reserved for `set`. 123 | 124 | Instead, use `frozenset([iterable])`. 125 | 126 | ### Mapping Types 127 | ```python3 128 | class 'dict' 129 | ``` 130 | 131 | See the [Dictionaries](#dictionaries) section for more info. 132 | 133 | [▲ TOP](#table-of-contents) 134 | ## Dictionaries 135 | ### Dictionary Iteration 136 | Get w/ default value if key not in dict: 137 | ```python 138 | my_dict[k] = my_dict.get(k, 0) + 1; # get retrieves value for k, or 0 if k not in dict 139 | ``` 140 | 141 | Iterating a dict iterates only the keys: 142 | ```python 143 | for k in my_dict: # k will be each key, not each key-value pair 144 | ... 145 | ``` 146 | 147 | Testing membership: `if k in dict: ...` 148 | 149 | To get actual key-value pairs at the same time: 150 | ```python 151 | for k,v in my_dict.items(): 152 | ... 153 | ``` 154 | applies to comprehensions as well: `new_d = {k: v+1 for k,v in d.items()}` 155 | 156 | ### Dictionary Sorting 157 | It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples. 158 | - `sorted(d.items())` 159 | - sorted list of key-value pairs by key 160 | - by value: `sorted(d.items(), key=lambda x: x[1]` 161 | - `sorted(d)` 162 | - sorted list of keys only 163 | - sorted list of keys by value: `sorted(d, key=lambda x: d[x])` 164 | 165 | [▲ TOP](#table-of-contents) 166 | ## Lists 167 | ### List Comprehensions 168 | General Syntax: 169 | ```python 170 | [ for item in list if conditional] 171 | ``` 172 | is equivalent to: 173 | ```python 174 | for item in list: 175 | if conditional: 176 | 177 | ``` 178 | 179 | Note how the order of the `for` and `if` statements remains the same. 180 | For example, 181 | ```python 182 | for row in grid: 183 | for x in row: 184 | 185 | ``` 186 | is the same as 187 | ```python 188 | [ for row in grid for x in row] 189 | ``` 190 | 191 | ### List Initialization 192 | Can use comprehensions: 193 | ```python 194 | my_list = [i for i in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 195 | ``` 196 | 2-D list (list of lists): 197 | ```python 198 | my_list = [[] for i in range(3)] # [[], [], []] 199 | ``` 200 | This is useful for a "visited" grid of some kind (common in Dynamic Programming problems): 201 | ```python 202 | visited = [[0 for i in range(len(grid[0]))] for j in range(len(grid))] 203 | ``` 204 | *BE CAREFUL* when initializing a matrix. 205 | Do this: 206 | ```python 207 | my_list = [[None] * n for i in range(n)] 208 | ``` 209 | **NOT** this: 210 | ```python 211 | my_list = [[None] * n] * n 212 | ``` 213 | The latter method makes copies of the **reference** to the original list, thus any modification to one row will change the other rows in the same way. The first method does not do this. 214 | 215 | A list can be created from a string using `list(my_str)` 216 | We can apply a filter as well: 217 | ```python 218 | my_list = list(c for c in my_str if c not in ('a', 'c', 'e')) 219 | ``` 220 | 221 | ### List Reversal 222 | - `my_list[::-1]` 223 | - returns copy of list in reverse 224 | - `reversed(my_list)` 225 | - returns an iterator on the list in reverse 226 | - can turn into a list via `list(reversed(my_list))` 227 | - `my_list.reverse()` 228 | - actually modifies the list 229 | 230 | ### List Sorting 231 | - `sorted(my_list)` 232 | - returns copy of sorted list 233 | - `my_list.sort()` 234 | - actually modifies the list 235 | 236 | By default, these methods will sort the list in ascending order. 237 | For descending order, we can supply the arg `reverse=True` to either of the aforementioned methods. 238 | 239 | We can also override the key for sorting by supplying the `key` arg. 240 | For example, if we have a list of tuples and we want to use the second item as the key: 241 | ```python 242 | list1 = [(1, 2), (3, 3), (4, 1)] 243 | list1.sort(key=lambda x: x[1]) # list1 is now [(4, 1), (1, 2), (3, 3)] 244 | ``` 245 | Additionally, if we want to sort in descending order: 246 | ```python 247 | list1.sort(key=lambda x: x[1], reverse=True) # list1 is now [(3, 3), (1, 2), (4, 1)] 248 | ``` 249 | 250 | When using `sorted()` it works the same, except we supply the list as the first arg: 251 | ```python 252 | list2 = sorted(list1, key=lambda x: x[1], reverse=True) 253 | ``` 254 | 255 | [▲ TOP](#table-of-contents) 256 | ## Strings 257 | ### From List 258 | ```python 259 | my_list = ['te', 's', 't', '1', '2', '3', '_'] 260 | s = ''.join(my_list) # "test123_" 261 | s2 = ''.join(c for c in my_list if c.isalnum()) # "test123" 262 | ``` 263 | 264 | ### String Constants 265 | Python has a lot of useful string constants. A few of them are shown below. 266 | For a complete list, see the [documentation](https://docs.python.org/3.7/library/string.html) 267 | - `string.ascii_letters` 268 | - `string.digits` 269 | - `string.whitespace` 270 | 271 | e.g. `if d in string.digits: ...` 272 | 273 | ### `isalnum()` 274 | Returns `True` if a string consists only of alphanumeric characters. 275 | ```python 276 | s = "test123" 277 | s.isalnum() # True 278 | ``` 279 | 280 | ### `split()` 281 | Return a list of the words in the string, using `sep` as the delimiter string. If `maxsplit` is given, at most `maxsplit` splits are done (thus, the list will have at most `maxsplit + 1` elements). If `maxsplit` is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made). 282 | Usage: 283 | ```python3 284 | str.split(sep=None, maxsplit=-1) 285 | ``` 286 | 287 | ```python3 288 | '1,2,3'.split(',') # ['1', '2', '3'] 289 | '1,2,3'.split(',', maxsplit=1) # ['1', '2,3'] 290 | '1,2,,3,'.split(',') # ['1', '2', '', '3', ''] 291 | ``` 292 | 293 | ### `strip()` 294 | Returns copy of string without surrounding whitespace, if any. 295 | ```python 296 | s = " test " 297 | s.strip() # "test" 298 | ``` 299 | 300 | ### `str()` vs `repr()` 301 | See [this GeeksForGeeks article](https://www.geeksforgeeks.org/str-vs-repr-in-python/) for more info. 302 | 303 | [▲ TOP](#table-of-contents) 304 | ## Iterators 305 | In Python, an iterator is an object with a countable number of values that can be iterated upon. 306 | An iterator is an object which implements the iterator protocol, consisting of `__iter__()` and `__next__()`. 307 | The `__iter__()` method returns an iterator on the object, and the `__next__()` method gets the next item using the iterator, or raises a `StopIteration` exception if the end of the iterable is reached. 308 | 309 | ### Iterator vs Iterable 310 | Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable *containers* which you can get an iterator from. 311 | All these objects have a `__iter__()` method which is used to get an iterator: 312 | ```python3 313 | mytuple = ("apple", "banana", "cherry") 314 | myit = iter(mytuple) 315 | 316 | print(next(myit)) # apple 317 | print(next(myit)) # banana 318 | print(next(myit)) # cherry 319 | print(next(myit)) # raises StopIteration exception 320 | ``` 321 | Note -- `next(obj)` is the same as `obj.__next__()`. 322 | 323 | 324 | ### How for loop actually works 325 | The `for` loop can iterate any iterable. 326 | The `for` loop in Python is actually implemented like so: 327 | ```python3 328 | iter_obj = iter(iterable) # create iterator object from iterable 329 | 330 | # infinite loop 331 | while True: 332 | try: 333 | element = next(iter_obj) # get the next item 334 | # do something with element 335 | except StopIteration: 336 | break 337 | ``` 338 | So, internally, the `for` loop creates an iterator object by calling `iter()` on the iterable, and then repeatedly calling `next()` until a `StopIteration` exception is raised. 339 | 340 | ### Creating an Iterator 341 | Here is an example of an iterator that will give us the next power of two in each iteration. 342 | ```python3 343 | class PowTwo: 344 | """Class to implement an iterator of powers of two""" 345 | 346 | def __init__(self, max = 0): 347 | self.max = max 348 | 349 | def __iter__(self): 350 | self.n = 0 351 | return self 352 | 353 | def __next__(self): 354 | if self.n <= self.max: 355 | result = 2 ** self.n 356 | self.n += 1 357 | return result 358 | else: 359 | raise StopIteration 360 | ``` 361 | 362 | Now we can use it as follows: 363 | ```python3 364 | >>> a = PowTwo(4) 365 | >>> i = iter(a) 366 | >>> next(i) 367 | 1 368 | >>> next(i) 369 | 2 370 | >>> next(i) 371 | 4 372 | >>> next(i) 373 | 8 374 | >>> next(i) 375 | 16 376 | >>> next(i) 377 | Traceback (most recent call last): 378 | ... 379 | StopIteration 380 | ``` 381 | Or, alternatively, using a `for` loop: 382 | ```python3 383 | >>> for i in PowTwo(5): 384 | ... print(i) 385 | ... 386 | 1 387 | 2 388 | 4 389 | 8 390 | 16 391 | 32 392 | ``` 393 | 394 | [▲ TOP](#table-of-contents) 395 | ## Functional Iteration 396 | For some good explanations and examples for the following functions, see [here](http://book.pythontips.com/en/latest/map_filter.html). 397 | 398 | Note that `map()` and `filter()` both return iterators, so if you want a list, you need to use `list()` on the output. However, this is typically better accomplished with list comprehensions or `for` loops for the sake of readability. 399 | 400 | ### `map()` 401 | `map()` applies a function to all the items in a list. 402 | ```python 403 | map(function_to_apply, list_of_inputs) 404 | ``` 405 | 406 | For example, the following code: 407 | ```python 408 | items = [1, 2, 3, 4, 5] 409 | squared = [] 410 | for i in items: 411 | squared.append(i**2) 412 | ``` 413 | can be accomplished more easily with `map()`: 414 | ```python3 415 | items = [1, 2, 3, 4, 5] 416 | squared = list(map(lambda x: x**2, items)) 417 | ``` 418 | 419 | ### `filter()` 420 | `filter()` creates a list of elements for which a function returns `True`. 421 | 422 | Here's an example: 423 | ```python3 424 | number_list = range(-5, 5) 425 | less_than_zero = list(filter(lambda x: x < 0, number_list)) 426 | print(less_than_zero) # [-5, -4, -3, -2, -1] 427 | ``` 428 | 429 | ### `reduce()` 430 | `reduce()` is used to perform a rolling computation on a list. 431 | 432 | Here's an example: 433 | ```python3 434 | from functools import reduce 435 | number_list = [1, 2, 3, 4] 436 | product = reduce((lambda x, y: x * y), number_list) # output: 24 437 | ``` 438 | 439 | Often times, an explicit `for` loop is more readable than using `reduce()`. 440 | But if you're trying to flex in an interview, and the problem calls for it, it could be a nice way to subtly show your understanding of functional programming. 441 | 442 | [▲ TOP](#table-of-contents) 443 | ## Decorators 444 | A [decorator](https://www.scaler.com/topics/python/python-decorators/) is a function returning another function, usually applied as a function transformation using the `@wrapper` syntax. This syntax is merely syntactic sugar. 445 | 446 | The following two function definitions are semantically equivalent: 447 | ```python3 448 | def f(...): 449 | ... 450 | f = staticmethod(f) 451 | 452 | @staticmethod 453 | def f(...): 454 | ... 455 | ``` 456 | 457 | ### @classmethod 458 | Transform a method into a class method. A class method receives the class as implicit first argument, just like how an instance method receives the instance. To declare a class method: 459 | ```python3 460 | class C: 461 | @classmethod 462 | def f(cls, arg1, arg2, ...): 463 | ... 464 | ``` 465 | 466 | A class method can be called either on the class (like `C.f()`) or on an instance (like `C().f()`). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. 467 | 468 | Note that class methods are not the same as C++ or Java static methods. If you want those, see [`@staticmethod`](#staticmethod). 469 | 470 | ### @staticmethod 471 | Transform a method into a static method. A static method does not receive an implicit first argument. To declare a static method: 472 | ```python3 473 | class C: 474 | @staticmethod 475 | def f(arg1, arg2, ...): 476 | ... 477 | ``` 478 | 479 | A static method can be called either on the class (like `C.f()`) or on an instance (like `C().f()`). Static methods in Python are similar to those found in Java or C++. 480 | 481 | ### @property 482 | Return a property attribute. 483 | Usage: 484 | ```python3 485 | property(fget=None, fset=None, fdel=None, doc=None) 486 | ``` 487 | `fget` is a function for getting an attribute value. `fset` is a function for setting an attribute value. `fdel` is a function for deleting an attribute value. `doc` creates a docstring for the attribute. 488 | 489 | The following is a typical use case for defining a managed attribute `x`: 490 | ```python3 491 | class C: 492 | def __init__(self): 493 | self._x = None 494 | 495 | def getx(self): 496 | return self._x 497 | 498 | def setx(self, value): 499 | self._x = value 500 | 501 | def delx(self): 502 | del self._x 503 | 504 | x = property(getx, setx, delx, "I'm the 'x' property.") 505 | ``` 506 | Or, equivalently: 507 | ```python3 508 | class C: 509 | def __init__(self): 510 | self._x = None 511 | 512 | @property 513 | def x(self): 514 | """I'm the 'x' property.""" 515 | return self._x 516 | 517 | @x.setter 518 | def x(self, value): 519 | self._x = value 520 | 521 | @x.deleter 522 | def x(self): 523 | del self._x 524 | ``` 525 | 526 | If `c` is an instance of `C`, then `c.x` will invoke the getter; `c.x = value` will invoke the setter; and `del c.x` the deleter. 527 | 528 | If `doc` is not provided, the property will copy `fget`'s docstring, if it exists. Thus, it is straightforward to create read-only properties with the `@property` decorator: 529 | ```python3 530 | class Parrot: 531 | def __init__(self): 532 | self._voltage = 100000 533 | 534 | @property 535 | def voltage(self): 536 | """Get the current voltage.""" 537 | return self._voltage 538 | ``` 539 | The `@property` decorator turns the `voltage()` method into a “getter” for a read-only attribute with the same name, and it sets the docstring for `voltage` to “Get the current voltage.” 540 | 541 | For more information, check out [the documentation](https://docs.python.org/3/library/functions.html#property) and [this Programiz article](https://www.programiz.com/python-programming/property). 542 | 543 | [▲ TOP](#table-of-contents) 544 | ## Generators 545 | Generators are simpler ways of creating [iterators](#iterators). The overhead of creating `__iter__()`, `__next__()`, raising `StopIteration`, and keeping track of state can all be handled internally by a generator. 546 | 547 | A generator is a function that returns an object (iterator) which we can iterate over, one value at a time. 548 | 549 | ### Using `yield` 550 | To create a generator, simply define a function using a `yield` statement. 551 | 552 | A function containing at least one `yield` statement (it may contain other `yield` and `return` statements) becomes a generator. 553 | 554 | Both `yield` and `return` return some value from a function. The difference is that, while a `return` statement terminates a function entirely, `yield` pauses the function, saving its state and continuing from where it left off in successive calls. 555 | 556 | Once a function yields, it is paused and control is transferred back to the caller. Local variables and their states are remembered between successive calls. When the function terminates, `StopIteration` is raised automatically on further calls. 557 | 558 | Below is a simple generator example, for the sake of demonstrating how generators work. 559 | ```python3 560 | def my_gen(): 561 | n = 1 562 | print('This is printed first') 563 | yield n 564 | 565 | n += 1 566 | print('This is printed second') 567 | yield n 568 | 569 | # Without for loop: 570 | a = my_gen() 571 | next(a) # 'This is printed first' 572 | next(a) # 'This is printed second' 573 | next(a) # Traceback ... StopIteration 574 | 575 | # With for loop: 576 | for item in my_gen(): 577 | print(item) 578 | ```` 579 | 580 | Below is a more typical example. Generators often use loops with a suitable terminating condition. 581 | ```python3 582 | def reverse(my_str): 583 | for i in range(len(my_str) - 1, -1, -1): 584 | yield my_str[i] 585 | 586 | for char in reverse("hello"): 587 | print(char) # prints each char reverse on a new line 588 | ``` 589 | Note that the above example works not just with strings, but also other kinds of iterables. 590 | 591 | ### Generator Expressions 592 | Generator expressions can be used to create an anonymous generator function. The syntax is similar to that of [list comprehensions](#list-comprehensions), but uses parentheses instead of square brackets. However, while a list comprehension produces the entire list, generator expressions produce one item at a time. 593 | 594 | Generator expressions are kind of lazy, producing items only when asked for. For this reason, using a generator expression is much more memory efficient than an equivalent list comprehension. 595 | 596 | ```python3 597 | items = [1, 3, 6] 598 | item_squared = (item**2 for item in items) 599 | print(next(item_squared)) # 1 600 | print(next(item_squared)) # 9 601 | print(next(item_squared)) # 36 602 | next(item_squared) # StopIteration 603 | ``` 604 | 605 | Generator expressions can be used inside function calls. When used in such a way, the round parentheses can be dropped. 606 | ```python3 607 | sum(x**2 for x in items) # 46 608 | max(x**2 for x in items) # 36 609 | ``` 610 | 611 | [▲ TOP](#table-of-contents) 612 | ## Other Useful Built-in Functions 613 | For a complete list of built-ins in Python 3, see [the documentation](https://docs.python.org/3/library/functions.html). 614 | ### `abs()` 615 | Returns the absolute value of a number, either an integer or floating point number. 616 | If the argument is a complex number, its magnitude is returned. 617 | 618 | ### `any()` 619 | Usage: 620 | ```python 621 | any(iterable) 622 | ``` 623 | `any()` takes any iterable as an argument and returns `True` if at least one element of the iterable is `True`. 624 | 625 | ```python 626 | any([1, 3, 4, 0]) # True 627 | any([0, False]) # False 628 | any([0, False, 5]) # True 629 | any([]) # False 630 | 631 | any("This is good") # True 632 | any("0") # True 633 | any("") # False 634 | ``` 635 | 636 | See [here](https://www.programiz.com/python-programming/methods/built-in/any) for more info. 637 | 638 | Check if any tuples contain a negative value: 639 | ```python 640 | if any(x < 0 or y < 0 for (x, y) in list_ranges): ... 641 | ``` 642 | 643 | ### `all()` 644 | ```python 645 | all(iterable) 646 | ``` 647 | `all()` takes any iterable as an argument and returns `True` if all the elements of the iterable are `True`. 648 | 649 | ```python 650 | all([1, 3, 4, 5]) # True 651 | all([0, False]) # False 652 | all([1, 3, 4, 0]) # False 653 | all([0, False, 5]) # False 654 | all([]) # True 655 | 656 | all("This is good") # True 657 | all("0") # True 658 | all("") # True 659 | ``` 660 | 661 | See [here](https://www.programiz.com/python-programming/methods/built-in/all) for more info. 662 | 663 | Check if all elements of a list are `x`: 664 | ```python 665 | if all(c == x for c in alst): ... 666 | ``` 667 | 668 | ### `chr()` 669 | Returns the string representing a character whose Unicode code point is the integer passed. 670 | 671 | For example, `chr(97)` returns the string `a`, while `chr(8364)` returns the string `€`. 672 | 673 | This is the inverse of [`ord()`](#ord). 674 | 675 | ### `enumerate()` 676 | Usage: 677 | ```python3 678 | enumerate(iterable, start=0) 679 | ``` 680 | Returns an enumerate object. `iterable` must be a sequence, iterator, or some object which suports iteration. The `__next__()` method of the iterator returned by `enumerate()` returns a tuple containing a count (from `start` which defaults to zero) and the values obtained from iterating over the iterable. 681 | 682 | Example: 683 | ```python3 684 | seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 685 | list(enumerate(seasons)) # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 686 | list(enumerate(seasons, start=1)) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] 687 | ``` 688 | This is equivalent to: 689 | ```python3 690 | def enumerate(sequence, start=0): 691 | n = start 692 | for elem in sequence: 693 | yield n, elem 694 | n += 1 695 | ``` 696 | 697 | ### `input()` 698 | Gets input from the user. 699 | Usage: 700 | ```python3 701 | input([prompt]) 702 | ``` 703 | 704 | Example: 705 | ```python3 706 | >>> s = input('-> ') 707 | -> Monty Python's Flying Circus 708 | >>> s 709 | "Monty Python's Flying Circus" 710 | ``` 711 | If the `prompt` arg is present, it is written to stdout without a trailing newline. 712 | 713 | ### `isinstance()` 714 | Usage: 715 | ```python3 716 | isinstance(object, classinfo) 717 | ``` 718 | 719 | Returns true if the `object` argument is an instance of the `classinfo` argument, or of a (direct, indirect, or virtual) subclass thereof. Returns false otherwise. 720 | 721 | If `classinfo` is a tuple of type objects, return true if `object` is an instance of any of *any* of these types. 722 | 723 | ### `len()` 724 | Return the length of an object. The argument may be a sequence (e.g. string, bytes, tuple, list, or range) or a collection (e.g. dictionary, set, frozen set). 725 | 726 | ### `max()` 727 | Returns the max item in an iterable, or the max of multiple arguments passed. 728 | 729 | ### `min()` 730 | Returns the min item in an iterable, or the min of multiple arguments passed. 731 | 732 | ### `ord()` 733 | Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. 734 | 735 | For example, `ord('a')` returns the integer 97. `ord('€')` (Euro sign) return 8364. 736 | 737 | This is the inverse of [`chr()`](#chr). 738 | 739 | ### `pow()` 740 | Usage: 741 | ```python3 742 | pow(x, y[, z]) 743 | ``` 744 | Return `x` to the power `y`; if `z` is present, return `x` to the power `y`, modulo `z` (computed more efficiently than `pow(x, y) % z`). 745 | `pow(x, y)` is equivalent to `x**y`. 746 | 747 | ### `type()` 748 | Usage: 749 | ```python3 750 | type(object) 751 | type(name, bases, dict) 752 | ``` 753 | 754 | With one argument, return the type of `object`. The return value is a type object and generally the same object as returned by `object.__class__`. 755 | 756 | E.g. 757 | ```python3 758 | x = 5 759 | type(x) # class 'int' 760 | ``` 761 | 762 | The [`isinstance()`](#isinstance) function is recommended for testing the type of an object, since it accounts for subclasses. 763 | 764 | [▲ TOP](#table-of-contents) 765 | ## Common Gotchas 766 | ### Nested List Initialization 767 | When creating a list of lists, be sure to use the following structure: 768 | ```python 769 | my_list = [[None] * n for i in range(n)] 770 | ``` 771 | Read the section on [list initialization](#list-initialization) to see why. 772 | 773 | ### Mutable Default Arguments 774 | If we try to do something like `def f(x, arr=[])` this will most likely create undesirable behavior. 775 | Default arguments are resolved *only once*, when the function is first defined. The same arg will be used in successive function calls. In the case of a mutable type like a list, this means that changes made to the list in one call will be carried over in successive calls. 776 | Instead, consider doing: 777 | ```python 778 | def f(x, arr=None): 779 | if not arr: arr = [] 780 | ``` 781 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate --------------------------------------------------------------------------------