# Python : Core : Functions - [library/functions](https://docs.python.org/3/library/functions.html) TODO MORE: dir, property, super, type ## By Topic **For Iterables** ```python ## Returning Scalars all( iterable ) # True if len == 0 or all elements are truthy any( iterable ) # True if len > 0 and at least one element is truthy max( iterable, *, [default, ]key=None ) # largest e or key( e ); if empty -> default of ValueError max( arg1, arg2, *args, [default, ]key=None ) # largest arg or key( arg ); if empty -> default of ValueError ## Returning Iterables filter( None, iterable ) # [ e for e in iterable if e ] filter( func, iterable ) # [ e for e in iterable if func( e ) ] map( func, iterable ) # [ func( e ) for e in iterable ] enumerate( iterable, start=0 ) # [ ( start++, e ) for e in iterable ] map( func, iterable1, ... ) # [ func( e1, ... ) for e1, ... in iterable1, ... ] zip( iterable1, ..., strict=False ) # [ ( e1, ... ) for e1, ... in iterable1, ... ] sorted( iterable, key=None, reverse=False ) # returns new list sorted by e or key( e ) reversed( iterable ) ``` ## Alphabetically - `abs( x )` ­— calls `__abs__()` on object (absolute value for int/float) - `aiter( async_iterable )` ­— calls `__aiter__()` to return async iterator - `all( iterable )` ­— `True` if iterable is empty or all elements are truthy - `anext( async_iterator[, default] )` ­— calls `__anext__()`; async variant of `next()` - `any( iterable )` ­— `True` if len > 0 and at least one element is truthy - `ascii( object )` ­— same as `repr()` but with non-ascii chars escaped - `bin( x )` ­— converts `int` to binary string like "0b0101"; calls `__index__()` if not already an `int` - `bool( x=False )` ­— *(class)* returns boolean value of `x`; subclass of `int`; cannot be subclassed - `breakpoint( *args, **kws )` ­— see [[Debugging]] - `bytearray( source=b''[, encoding[, errors]] )` ­— *(class)* mutable sequence of 8-bit integers; length and initial contents depend on `source` type and value ([details](https://docs.python.org/3/library/functions.html#func-bytearray)) - `bytes( source=b''[, encoding[, errors]] )` ­— *(class)* immutable version of `bytearray` - `callable( object )` ­— whether `object` is callable (checks classes for `__call__()` method) - `chr( i )` ­— converts `int` to unicode character: `char( 97 ) -> 'a'`; inverse of `ord()` - `classmethod( func )` ­— transform instance method into class method - `compile( ... )` ­— compile source into code or AST object ([details](https://docs.python.org/3/library/functions.html#compile)) - `complex( [ real=0, imag=0 | string ] )` ­— *(class)* returns complex number - `delattr( object, name )` ­— equiv to: `del object.name` - `dict( [ [mapping | iterable, ]**kwargs] )` ­— *(class)* returns `dict` populated by contents of `mapping`, `iterable` *(sequence of k/v pairs)*, and `kwargs`, if any — else, `{}` - `dir( [object] )` ­— ? - `divmod( a, b )` ­— returns pair of numbers; for `ints`, equiv to: `( a // b, a % b )` - `enumerate( iterable, start=0 )` ­— turn sequence of values into pairs with index: `list(enumerate([ 'x', 'y' ])) -> [ (0,'x'), (1,'y') ]` - `eval( expression, globals=None, locals=None )` ­— executes Python string or code object containing a single expression and returns result; `globals` must be a `dict`, locals can be any mapping object - `exec( object, globals=None, locals=None, /, *, closure=None )` ­— executes Python string or code object containing any number of statements and returns None; `globals` must be a `dict`, locals can be any mapping object - `filter( function, iterable )` ­— equiv to: `i for i in iterable if function( i )` - if `function` is None, filters out falsy values - `float( x=0.0 )` ­— *(class)* returns `x` as float; if `x` is an object, calls `__float__()` or `__index__()` - `format( value, format_spec='' )` ­— see [[Strings#2. `format()` Family|Formatting]] - `frozenset( iterable=set() )` ­— *(class)* returns `frozenset` populated by `iterable` - `getattr( object, name[, default] )` ­— equiv to: `object.name` if exists, else `default` (if exists) - `globals()` ­— returns `dict` for current module namespace - `hasattr( object, name )` ­— whether `object` has attribute `name` - `hash( object )` ­— returns hash value (`int`) of `object` if exists when used as `dict` key; calls `__hash__()` if exists - `help( [request] )` ­— for interactive use - `hex( x )` ­— converts `int` to lowercase hex string like "0x1fe9"; calls `__index__()` if not already an `int` - `id( object )` ­— returns constant and unique `int` representing `object` identity - `input( [prompt] )` ­— prompt user for console input ([details](https://docs.python.org/3/library/functions.html#input)) - `int( x=0[, base=10] )` ­— *(class)* convert number or `string`/`bytes`/`bytearray` to `int`, rounding `floats` down; if exists, calls `__int__()` or `__index__()` - `isinstance( object, classinfo )` ­— whether `object` is an instance of a type that *is* or *is descended from* `classinfo`, which can also be a tuple of types - `issubclass( class, classinfo )` ­— whether `class` *is* or *is descended from* `classinfo`, which can also be a tuple of types - `iter( object )` ­— returns iterator for `object` (which must be a collection) by calling `__iter__()` or `__getitem__( 0 )` - `iter( object[, sentinel] )` ­— returns iterator which calls `object` (which must be a callable) with no arguments until the returned value == sentinel, then raises `StopIteration` - `len( s )` ­— returns "length" (number of items) in `s`, which must be a sequence or collection - `list( iterable=None )` ­— *(class)* returns `list` with contents of `iterable` if `iterable`, else `[]` - `locals()` ­— returns `dict` for current local symbol table; identical to `globals()` at the module level - `map( function, iterable )` ­— returns iterator that applies `function` to every item of `iterable`: `squared = map( square, numbers )` - `map( function, *iterables )` — as above, but `function` must take the same number of args as the number of `iterables`, all of which will be iterated in parallel - `max( iterable, *, [default, ]key=None )` ­— returns largest value of `iterable`, or largest return value of `key( i )` if provided; if `iterable` is empty, returns `default` (if provided) or raises `ValueError` - `max( arg1, arg2, *args, key=None )` — returns largest arg, or largest return value of `key( arg )` if provided - `memoryview( object )` ­— *(class)* returns `memoryview` instance that references `object` - `min( iterable, *, [default, ]key=None )`, `min( arg1, arg2, *args, key=None )` ­— opposite of `max()` - `next( iterator[, default] )` ­— returns next item from `iterator` by calling `__next__()`; if exhausted, returns `default` (if provided) or raises `StopIteration` - `object` ­— *(class)* base for all classes; has no `__dict__`, returns new featureless object - `oct( x )` ­— converts `int` to octal string like "0o1073"; calls `__index__()` if not already an `int` - `open( file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None )` — opens file and returns file object or raises `OSError`; see [[Files & Dirs#The `open` Built-in Function|Files & Dirs]] - `ord( c )` ­— converts unicode character to `int`: `ord( 'a' ) -> 97`; inverse of `chr() - `pow( base, exp, mode=None )` ­— returns `base` to the power of `exp`; equiv to: `base**exp` - `print( *objects, sep=' ', end='\n', file=None, flush=False )` ­— converts `objects` to strings with `str()`; if none, prints `end`; `file` must have a `write()` method (defaults to `sys.stdout) - `property( fget=None, fset=None, fdel=None, doc=None )` ­— *(class)* ? - `range( stop ) or range( start, stop, step=1 )` ­— *(class)* returns iterable `range` instance - `repr( object )` ­— calls `__repr__()`, which should return a text representation that can recreate the object - `reversed( seq )` ­— returns a reverse iterator; `seq` must support either `__reversed__()` or `__len__()` + `__getitem__( 0 )` - `round( number, ndigits=None )` ­— rounds `0.5` to `0` but `1.5` to `2` ([details](https://docs.python.org/3/library/functions.html#round)) - `set( [iterable] )` ­— *(class)* returns `set` populated by `iterable` - `setattr( object, name, value )` ­— equiv to: `object.name = value` - `slice( [start, ]stop[, step=None] )` ­— *(class)* takes same args as `range()` and returns `slice` instance with three attributes (`start`, `stop`, `step`) - `sorted( iterable, /, *, key=None, reverse=False )` ­— returns new sorted `list`; requires at least `__lt__()`, although implementing all six comparisons is recommended - `staticmethod( func )` ­— transform instance method into static method - `str( [ object='' | object=b'', encoding='utf-8', errors='strict' ] )` ­— *(class)* returns `str` version of `object` if `object` else `''`; if `encoding` or `errors`, `object` must be `bytes`, and result eq: `bytes.decode( encoding, errors )`; else, result eq: `type( object ).__str__( object ) or repr( object )` - `sum( iterable, / start=0 )` ­— meant for numbers; for strings, use `''.join()`; for floats, use `math.fsum()`; to concatenate iterables, use `itertools.chain()` - `super( [type, object_or_type=None] )` ­— *(class)* ? - `tuple( [iterable] )` ­— *(class)* returns `tuple` with contents of `iterable` if `iterable` else empty tuple - `type( [ object | name, bases, dict, **kwds ] )` ­— *(class)* ? - `vars( [object] )` ­— returns `object.__dict__` if `object` else `locals()`; raises `TypeError` if `object` has no `__dict__` - `zip( *iterables, strict=False )` ­— returns iterator that produces tuples with one value from each of the `iterables` - `__import__( name, globals=None, locals=None, fromlist=(), level=0 )` ­— you probably don't need to use it