{"id":16637094,"url":"https://github.com/yungnickyoung/python-3-cheatsheet","last_synced_at":"2025-03-21T15:31:48.762Z","repository":{"id":107402910,"uuid":"196652936","full_name":"yungnickyoung/Python-3-Cheatsheet","owner":"yungnickyoung","description":"Python 3 notes cheatsheet, focusing on fundamentals and useful interview tips","archived":false,"fork":false,"pushed_at":"2022-09-14T16:04:37.000Z","size":36,"stargazers_count":67,"open_issues_count":1,"forks_count":11,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-03-18T02:44:27.636Z","etag":null,"topics":["cheatsheet","python","python-3"],"latest_commit_sha":null,"homepage":"https://yungnickyoung.github.io/Python-3-Cheatsheet/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yungnickyoung.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2019-07-12T22:26:29.000Z","updated_at":"2025-03-12T10:42:18.000Z","dependencies_parsed_at":"2023-03-13T14:36:29.963Z","dependency_job_id":null,"html_url":"https://github.com/yungnickyoung/Python-3-Cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FPython-3-Cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FPython-3-Cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FPython-3-Cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FPython-3-Cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yungnickyoung","download_url":"https://codeload.github.com/yungnickyoung/Python-3-Cheatsheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244822714,"owners_count":20516154,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","python","python-3"],"created_at":"2024-10-12T06:24:13.246Z","updated_at":"2025-03-21T15:31:48.491Z","avatar_url":"https://github.com/yungnickyoung.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"## Table of Contents\n- [Built-in Types](#built-in-types)\n  - [Boolean Types](#boolean-types)\n  - [Numeric Types](#numeric-types)\n  - [Sequence Types](#sequence-types)\n    - [Mutable Sequences](#mutable-sequences)\n    - [Immutable Sequences](#immutable-sequences)\n  - [Set Types](#set-types)\n  - [Mapping Types](#mapping-types)\n- [Dictionaries](#dictionaries)\n  - [Iteration](#dictionary-iteration)\n  - [Sorting](#dictionary-sorting)\n- [Lists](#lists)\n  - [Comprehensions](#list-comprehensions)\n  - [Initialization](#list-initialization)\n  - [Reversal](#list-reversal)\n  - [Sorting](#list-sorting)\n- [Strings](#strings)\n  - [From List](#from-list)\n  - [Python String Constants](#string-constants)\n  - [`isalnum()`](#isalnum)\n  - [`split()`](#split)\n  - [`strip()`](#strip)\n  - [`str()` vs `repr()`](#str-vs-repr)\n- [Iterators](#iterators)\n  - [Iterator vs Iterable](#iterator-vs-iterable)\n  - [How for loop actually works](#how-for-loop-actually-works)\n  - [Creating an Iterator](#creating-an-iterator)\n- [Functional Iteration](#functional-iteration)\n  - [`map()`](#map)\n  - [`filter()`](#filter)\n  - [`reduce()`](#reduce)\n- [Decorators](#decorators)\n  - [`@classmethod`](#classmethod)\n  - [`@staticmethod`](#staticmethod)\n  - [`@property`](#property)\n- [Generators](#generators)\n  - [Using `yield`](#using-yield)\n  - [Generator Expressions](#generator-expressions)\n- [Other Useful Built-in Functions](#other-useful-built-in-functions)\n  - [`abs()`](#abs)\n  - [`any()`](#any)\n  - [`all()`](#all)\n  - [`chr()`](#chr)\n  - [`enumerate()`](#enumerate)\n  - [`input()`](#input)\n  - [`isinstance()`](#isinstance)\n  - [`len()`](#len)\n  - [`max()`](#max)\n  - [`min()`](#min)\n  - [`ord()`](#ord)\n  - [`pow()`](#pow)\n  - [`type()`](#type) \n- [Common Gotchas](#common-gotchas)\n  - [Nested List Initialization](#nested-list-initialization)\n  - [Mutable Default Arguments](#mutable-default-arguments)\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Built-in Types\nIn 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)\n\n### Boolean Types\n```python3\nclass 'bool'\n```\n\nBy 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`:\n- constants defined to be false: `None` and `False`\n- zero of any numeric type: `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)`\n- empty sequences and collections: `''`, `()`, `[]`, `{}`, `set()`, `range(0)`\n\n### Numeric Types\n```python3\nclass 'int'\nclass 'float'\nclass 'complex'\n```\n\nIntegers 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).\n\nThe 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.\n\n### Sequence Types\nImmutable 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.\n\n#### Mutable Sequences\n```python3\nclass 'list'\nclass 'bytearray\n```\n\n`bytearray` objects are a mutable counterpart to `bytes` objects.\n\n#### Immutable Sequences\n```python3\nclass 'tuple'\nclass 'range'\nclass 'str'\nclass 'bytes'\n```\n\n`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:  \n- Single quotes: `b'still allows embedded \"double\" quotes'`\n- Double quotes: `b\"still allows embedded 'single' quotes\"`\n- Triple quotes: `b'''3 single quotes'''`, `b\"\"\"3 double quotes\"\"\"`\n\nOnly ASCII chars are permitted in `bytes` literals.  \n`bytes` objects actually behave like immutable sequences of integers, with each value restricted to `0 \u003c= x \u003c 256`.\n\n`bytes` objects can be created in several ways:\n- A zero-filled bytes object of a specific length: `bytes(10)`\n- From an iterable of integers: `bytes(range(20))`\n- Copying existing binary data via the buffer protocol: `bytes(obj)`\n\n### Set Types\n```python3\nclass 'set'\nclass 'frozenset'\n```\n\n`set` is mutable, while `frozenset` is immutable.  \nNote 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`.\n\nInstead, use `frozenset([iterable])`.\n\n### Mapping Types\n```python3\nclass 'dict'\n```\n\nSee the [Dictionaries](#dictionaries) section for more info.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Dictionaries\n### Dictionary Iteration\nGet w/ default value if key not in dict:\n```python\nmy_dict[k] = my_dict.get(k, 0) + 1; # get retrieves value for k, or 0 if k not in dict\n```\n\nIterating a dict iterates only the keys:\n```python\nfor k in my_dict:  # k will be each key, not each key-value pair\n    ...\n```\n\nTesting membership: `if k in dict: ...`\n\nTo get actual key-value pairs at the same time:\n```python\nfor k,v in my_dict.items():\n    ...\n```\napplies to comprehensions as well: `new_d = {k: v+1 for k,v in d.items()}`\n\n### Dictionary Sorting\nIt 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.  \n- `sorted(d.items())`\n  - sorted list of key-value pairs by key\n  - by value: `sorted(d.items(), key=lambda x: x[1]`\n- `sorted(d)`\n  - sorted list of keys only\n  - sorted list of keys by value: `sorted(d, key=lambda x: d[x])`\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Lists\n### List Comprehensions\nGeneral Syntax:\n```python\n[\u003cexpression\u003e for item in list if conditional]\n```\nis equivalent to:\n```python\nfor item in list:\n    if conditional:\n        \u003cexpression\u003e\n```\n\nNote how the order of the `for` and `if` statements remains the same.\nFor example, \n```python\nfor row in grid:\n    for x in row:\n        \u003cexpression\u003e\n```\nis the same as\n```python\n[\u003cexpression\u003e for row in grid for x in row]\n```\n\n### List Initialization\nCan use comprehensions:\n```python\nmy_list = [i for i in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n2-D list (list of lists):\n```python\nmy_list = [[] for i in range(3)] # [[], [], []]\n```\nThis is useful for a \"visited\" grid of some kind (common in Dynamic Programming problems):\n```python\nvisited = [[0 for i in range(len(grid[0]))] for j in range(len(grid))]\n```\n*BE CAREFUL* when initializing a matrix.\nDo this:\n```python\nmy_list = [[None] * n for i in range(n)]\n```\n**NOT** this:\n```python\nmy_list = [[None] * n] * n\n```\nThe 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.\n\nA list can be created from a string using `list(my_str)`\nWe can apply a filter as well:\n```python\nmy_list = list(c for c in my_str if c not in ('a', 'c', 'e'))\n```\n\n### List Reversal\n - `my_list[::-1]`\n   - returns copy of list in reverse\n - `reversed(my_list)`\n   - returns an iterator on the list in reverse\n   - can turn into a list via `list(reversed(my_list))`\n - `my_list.reverse()`\n   - actually modifies the list\n \n### List Sorting\n - `sorted(my_list)`\n   - returns copy of sorted list\n - `my_list.sort()`\n   - actually modifies the list\n   \n By default, these methods will sort the list in ascending order.\n For descending order, we can supply the arg `reverse=True` to either of the aforementioned methods.\n \n We can also override the key for sorting by supplying the `key` arg.\n For example, if we have a list of tuples and we want to use the second item as the key:\n ```python\n list1 = [(1, 2), (3, 3), (4, 1)] \n list1.sort(key=lambda x: x[1]) # list1 is now [(4, 1), (1, 2), (3, 3)]\n ```\n Additionally, if we want to sort in descending order:\n ```python\n list1.sort(key=lambda x: x[1], reverse=True) # list1 is now [(3, 3), (1, 2), (4, 1)]\n ```\n \n When using `sorted()` it works the same, except we supply the list as the first arg:\n ```python\n list2 = sorted(list1, key=lambda x: x[1], reverse=True)\n ```\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Strings\n### From List\n```python\nmy_list = ['te', 's', 't', '1', '2', '3', '_']\ns = ''.join(my_list) # \"test123_\"\ns2 = ''.join(c for c in my_list if c.isalnum()) # \"test123\"\n```\n\n### String Constants\nPython has a lot of useful string constants. A few of them are shown below.\nFor a complete list, see the [documentation](https://docs.python.org/3.7/library/string.html)\n - `string.ascii_letters`\n - `string.digits`\n - `string.whitespace`\n \n e.g. `if d in string.digits: ...`\n \n### `isalnum()`\nReturns `True` if a string consists only of alphanumeric characters.\n```python\ns = \"test123\"\ns.isalnum() # True\n```\n\n### `split()`\nReturn 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).  \nUsage:\n```python3\nstr.split(sep=None, maxsplit=-1)\n```\n\n```python3\n'1,2,3'.split(',')             # ['1', '2', '3']\n'1,2,3'.split(',', maxsplit=1) # ['1', '2,3']\n'1,2,,3,'.split(',')           # ['1', '2', '', '3', '']\n```\n\n### `strip()`\nReturns copy of string without surrounding whitespace, if any.\n```python\ns = \"   test \"\ns.strip() # \"test\"\n```\n\n### `str()` vs `repr()`\nSee [this GeeksForGeeks article](https://www.geeksforgeeks.org/str-vs-repr-in-python/) for more info.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Iterators\nIn Python, an iterator is an object with a countable number of values that can be iterated upon.\nAn iterator is an object which implements the iterator protocol, consisting of `__iter__()` and `__next__()`.  \nThe `__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.\n\n### Iterator vs Iterable\nLists, tuples, dictionaries, and sets are all iterable objects. They are iterable *containers* which you can get an iterator from.\nAll these objects have a `__iter__()` method which is used to get an iterator:\n```python3\nmytuple = (\"apple\", \"banana\", \"cherry\")\nmyit = iter(mytuple)\n\nprint(next(myit)) # apple\nprint(next(myit)) # banana\nprint(next(myit)) # cherry\nprint(next(myit)) # raises StopIteration exception\n```\nNote -- `next(obj)` is the same as `obj.__next__()`.\n\n\n### How for loop actually works\nThe `for` loop can iterate any iterable.  \nThe `for` loop in Python is actually implemented like so:\n```python3\niter_obj = iter(iterable) # create iterator object from iterable\n\n# infinite loop\nwhile True:\n    try:\n        element = next(iter_obj) # get the next item\n        # do something with element\n    except StopIteration:\n        break\n```\nSo, 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.\n\n### Creating an Iterator\nHere is an example of an iterator that will give us the next power of two in each iteration.\n```python3\nclass PowTwo:\n    \"\"\"Class to implement an iterator of powers of two\"\"\"\n\n    def __init__(self, max = 0):\n        self.max = max\n\n    def __iter__(self):\n        self.n = 0\n        return self\n\n    def __next__(self):\n        if self.n \u003c= self.max:\n            result = 2 ** self.n\n            self.n += 1\n            return result\n        else:\n            raise StopIteration\n```\n\nNow we can use it as follows:\n```python3\n\u003e\u003e\u003e a = PowTwo(4)\n\u003e\u003e\u003e i = iter(a)\n\u003e\u003e\u003e next(i)\n1\n\u003e\u003e\u003e next(i)\n2\n\u003e\u003e\u003e next(i)\n4\n\u003e\u003e\u003e next(i)\n8\n\u003e\u003e\u003e next(i)\n16\n\u003e\u003e\u003e next(i)\nTraceback (most recent call last):\n...\nStopIteration\n```\nOr, alternatively, using a `for` loop:\n```python3\n\u003e\u003e\u003e for i in PowTwo(5):\n...     print(i)\n...     \n1\n2\n4\n8\n16\n32\n```\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Functional Iteration\nFor some good explanations and examples for the following functions, see [here](http://book.pythontips.com/en/latest/map_filter.html).\n\nNote 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.\n  \n### `map()`\n`map()` applies a function to all the items in a list.\n```python\nmap(function_to_apply, list_of_inputs)\n```\n  \nFor example, the following code:\n```python\nitems = [1, 2, 3, 4, 5]\nsquared = []\nfor i in items:\n    squared.append(i**2)\n```\ncan be accomplished more easily with `map()`:\n```python3\nitems = [1, 2, 3, 4, 5]\nsquared = list(map(lambda x: x**2, items))\n```\n\n### `filter()`\n`filter()` creates a list of elements for which a function returns `True`.\n  \nHere's an example:\n```python3\nnumber_list = range(-5, 5)\nless_than_zero = list(filter(lambda x: x \u003c 0, number_list))\nprint(less_than_zero) # [-5, -4, -3, -2, -1]\n```\n\n### `reduce()`\n`reduce()` is used to perform a rolling computation on a list.\n\nHere's an example:\n```python3\nfrom functools import reduce\nnumber_list = [1, 2, 3, 4]\nproduct = reduce((lambda x, y: x * y), number_list) # output: 24\n```\n\nOften times, an explicit `for` loop is more readable than using `reduce()`.\nBut 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.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Decorators\nA [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.\n\nThe following two function definitions are semantically equivalent:\n```python3\ndef f(...):\n    ...\nf = staticmethod(f)\n\n@staticmethod\ndef f(...):\n    ...\n```\n\n### @classmethod\nTransform 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:\n```python3\nclass C:\n    @classmethod\n    def f(cls, arg1, arg2, ...):\n        ...\n```\n\nA 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.\n\nNote that class methods are not the same as C++ or Java static methods. If you want those, see [`@staticmethod`](#staticmethod).\n\n### @staticmethod\nTransform a method into a static method. A static method does not receive an implicit first argument. To declare a static method:\n```python3\nclass C:\n    @staticmethod\n    def f(arg1, arg2, ...):\n        ...\n```\n\nA 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++.\n\n### @property\nReturn a property attribute.\nUsage:\n```python3\nproperty(fget=None, fset=None, fdel=None, doc=None)\n```\n`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.\n\nThe following is a typical use case for defining a managed attribute `x`:\n```python3\nclass C:\n    def __init__(self):\n        self._x = None\n\n    def getx(self):\n        return self._x\n\n    def setx(self, value):\n        self._x = value\n\n    def delx(self):\n        del self._x\n\n    x = property(getx, setx, delx, \"I'm the 'x' property.\")\n```\nOr, equivalently:\n```python3\nclass C:\n    def __init__(self):\n        self._x = None\n\n    @property\n    def x(self):\n        \"\"\"I'm the 'x' property.\"\"\"\n        return self._x\n\n    @x.setter\n    def x(self, value):\n        self._x = value\n\n    @x.deleter\n    def x(self):\n        del self._x\n```    \n\nIf `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.\n\nIf `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:\n```python3\nclass Parrot:\n    def __init__(self):\n        self._voltage = 100000\n\n    @property\n    def voltage(self):\n        \"\"\"Get the current voltage.\"\"\"\n        return self._voltage\n```\nThe `@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.”\n\nFor 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).\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Generators\nGenerators 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.\n\nA generator is a function that returns an object (iterator) which we can iterate over, one value at a time. \n\n### Using `yield`\nTo create a generator, simply define a function using a `yield` statement.\n\nA function containing at least one `yield` statement (it may contain other `yield` and `return` statements) becomes a generator.\n\nBoth `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.\n\nOnce 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.\n\nBelow is a simple generator example, for the sake of demonstrating how generators work.\n```python3\ndef my_gen():\n    n = 1\n    print('This is printed first')\n    yield n\n\n    n += 1\n    print('This is printed second')\n    yield n\n    \n# Without for loop:\na = my_gen()\nnext(a) # 'This is printed first'\nnext(a) # 'This is printed second'\nnext(a) # Traceback ... StopIteration\n\n# With for loop:\nfor item in my_gen():\n    print(item)\n````\n\nBelow is a more typical example. Generators often use loops with a suitable terminating condition.\n```python3\ndef reverse(my_str):\n    for i in range(len(my_str) - 1, -1, -1):\n        yield my_str[i]\n        \nfor char in reverse(\"hello\"):\n    print(char) # prints each char reverse on a new line\n```\nNote that the above example works not just with strings, but also other kinds of iterables.\n\n### Generator Expressions\nGenerator 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.\n\nGenerator 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.\n\n```python3\nitems = [1, 3, 6]\nitem_squared = (item**2 for item in items)\nprint(next(item_squared)) # 1\nprint(next(item_squared)) # 9\nprint(next(item_squared)) # 36\nnext(item_squared) # StopIteration\n```\n\nGenerator expressions can be used inside function calls. When used in such a way, the round parentheses can be dropped.\n```python3\nsum(x**2 for x in items) # 46\nmax(x**2 for x in items) # 36\n```\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Other Useful Built-in Functions\nFor a complete list of built-ins in Python 3, see [the documentation](https://docs.python.org/3/library/functions.html).\n### `abs()`\nReturns the absolute value of a number, either an integer or floating point number.\nIf the argument is a complex number, its magnitude is returned.\n\n### `any()`\nUsage:\n```python\nany(iterable)\n```\n`any()` takes any iterable as an argument and returns `True` if at least one element of the iterable is `True`.\n\n```python\nany([1, 3, 4, 0])   # True\nany([0, False])     # False\nany([0, False, 5])  # True\nany([])             # False\n\nany(\"This is good\") # True\nany(\"0\")            # True\nany(\"\")             # False\n```\n\nSee [here](https://www.programiz.com/python-programming/methods/built-in/any) for more info.\n\nCheck if any tuples contain a negative value:\n```python\nif any(x \u003c 0 or y \u003c 0 for (x, y) in list_ranges): ...\n```\n\n### `all()`\n```python\nall(iterable)\n```\n`all()` takes any iterable as an argument and returns `True` if all the elements of the iterable are `True`.\n\n```python\nall([1, 3, 4, 5])  # True\nall([0, False])    # False\nall([1, 3, 4, 0])  # False\nall([0, False, 5]) # False\nall([])            # True\n\nall(\"This is good\") # True\nall(\"0\")            # True\nall(\"\")             # True\n```\n\nSee [here](https://www.programiz.com/python-programming/methods/built-in/all) for more info.\n\nCheck if all elements of a list are `x`: \n```python\nif all(c == x for c in alst): ...\n```\n\n### `chr()`\nReturns the string representing a character whose Unicode code point is the integer passed.\n\nFor example, `chr(97)` returns the string `a`, while `chr(8364)` returns the string `€`.\n\nThis is the inverse of [`ord()`](#ord).\n\n### `enumerate()`\nUsage:\n```python3\nenumerate(iterable, start=0)\n```\nReturns 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.  \n\nExample:\n```python3\nseasons = ['Spring', 'Summer', 'Fall', 'Winter']\nlist(enumerate(seasons))              # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]\nlist(enumerate(seasons, start=1))     # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]\n```\nThis is equivalent to:\n```python3\ndef enumerate(sequence, start=0):\n    n = start\n    for elem in sequence:\n        yield n, elem\n        n += 1\n```\n\n### `input()`\nGets input from the user.\nUsage:\n```python3\ninput([prompt])\n```\n\nExample: \n```python3\n\u003e\u003e\u003e s = input('-\u003e ')  \n-\u003e Monty Python's Flying Circus\n\u003e\u003e\u003e s  \n\"Monty Python's Flying Circus\"\n```\nIf the `prompt` arg is present, it is written to stdout without a trailing newline.\n\n### `isinstance()`\nUsage:\n```python3\nisinstance(object, classinfo)\n```\n\nReturns true if the `object` argument is an instance of the `classinfo` argument, or of a (direct, indirect, or virtual) subclass thereof. Returns false otherwise.\n\nIf `classinfo` is a tuple of type objects, return true if `object` is an instance of any of *any* of these types.\n\n### `len()`\nReturn 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).\n\n### `max()`\nReturns the max item in an iterable, or the max of multiple arguments passed.\n\n### `min()`\nReturns the min item in an iterable, or the min of multiple arguments passed.\n\n### `ord()`\nGiven a string representing one Unicode character, return an integer representing the Unicode code point of that character.\n\nFor example, `ord('a')` returns the integer 97. `ord('€')` (Euro sign) return 8364. \n\nThis is the inverse of [`chr()`](#chr).\n\n### `pow()`\nUsage:\n```python3\npow(x, y[, z])\n```\nReturn `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`).  \n`pow(x, y)` is equivalent to `x**y`.\n\n### `type()`\nUsage:\n```python3\ntype(object)\ntype(name, bases, dict)\n```\n\nWith one argument, return the type of `object`. The return value is a type object and generally the same object as returned by `object.__class__`.\n\nE.g.\n```python3\nx = 5\ntype(x)  # class 'int'\n```\n\nThe [`isinstance()`](#isinstance) function is recommended for testing the type of an object, since it accounts for subclasses.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Common Gotchas\n### Nested List Initialization\nWhen creating a list of lists, be sure to use the following structure:\n```python\nmy_list = [[None] * n for i in range(n)]\n```\nRead the section on [list initialization](#list-initialization) to see why.\n\n### Mutable Default Arguments\nIf we try to do something like `def f(x, arr=[])` this will most likely create undesirable behavior.\nDefault 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.\nInstead, consider doing:\n```python\ndef f(x, arr=None):\n    if not arr: arr = []\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyungnickyoung%2Fpython-3-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyungnickyoung%2Fpython-3-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyungnickyoung%2Fpython-3-cheatsheet/lists"}