Help on built-in functions in module builtins (74)

built-in function

Version1

01. abs()

Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

===========================================================================
02. aiter()

Help on built-in function aiter in module builtins:

aiter(async_iterable, /)
    Return an AsyncIterator for an AsyncIterable object.

===========================================================================
03. all()

Help on built-in function all in module builtins:

all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.
    
    If the iterable is empty, return True.

===========================================================================
04. anext()

Help on built-in function anext in module builtins:

anext(...)
    async anext(aiterator[, default])
    
    Return the next item from the async iterator.  If default is given and the async
    iterator is exhausted, it is returned instead of raising StopAsyncIteration.

===========================================================================
05. any()

Help on built-in function any in module builtins:

any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.

===========================================================================
06. ascii()

Help on built-in function ascii in module builtins:

ascii(obj, /)
    Return an ASCII-only representation of an object.
    
    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \\x, \\u or \\U escapes. This generates a string similar
    to that returned by repr() in Python 2.

===========================================================================
07. bin()

Help on built-in function bin in module builtins:

bin(number, /)
    Return the binary representation of an integer.
    
    >>> bin(2796202)
    '0b1010101010101010101010'

===========================================================================
09. breakpoint()

Help on built-in function breakpoint in module builtins:

breakpoint(...)
    breakpoint(*args, **kws)
    
    Call sys.breakpointhook(*args, **kws).  sys.breakpointhook() must accept
    whatever arguments are passed.
    
    By default, this drops you into the pdb debugger.

===========================================================================
12. callable()

Help on built-in function callable in module builtins:

callable(obj, /)
    Return whether the object is callable (i.e., some kind of function).
    
    Note that classes are callable, as are instances of classes with a
    __call__() method.

===========================================================================
13. chr()

Help on built-in function chr in module builtins:

chr(i, /)
    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

===========================================================================
15. compile()

Help on built-in function compile in module builtins:

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-1)
    Compile source into a code object that can be executed by exec() or eval().
    
    The source code may represent a Python module, statement or expression.
    The filename will be used for run-time error messages.
    The mode must be 'exec' to compile a module, 'single' to compile a
    single (interactive) statement, or 'eval' to compile an expression.
    The flags argument, if present, controls which future statements influence
    the compilation of the code.
    The dont_inherit argument, if true, stops the compilation inheriting
    the effects of any future statements in effect in the code calling
    compile; if absent or false these statements do influence the compilation,
    in addition to any features explicitly specified.

===========================================================================
19. delattr()

Help on built-in function delattr in module builtins:

delattr(obj, name, /)
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''

===========================================================================
21. dir()

Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

===========================================================================
22. divmod()

Help on built-in function divmod in module builtins:

divmod(x, y, /)
    Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.

===========================================================================
24. eval()

Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

===========================================================================
25. exec()

Help on built-in function exec in module builtins:

exec(source, globals=None, locals=None, /, *, closure=None)
    Execute the given source in the context of globals and locals.
    
    The source may be a string representing one or more Python statements
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
    The closure must be a tuple of cellvars, and can only be used
    when source is a code object requiring exactly that many cellvars.

===========================================================================
31. getattr()

Help on built-in function getattr in module builtins:

getattr(...)
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.

===========================================================================
32. globals()

Help on built-in function globals in module builtins:

globals()
    Return the dictionary containing the current scope's global variables.
    
    NOTE: Updates to this dictionary *will* affect name lookups in the current
    global scope and vice-versa.

===========================================================================
33. hasattr()

Help on built-in function hasattr in module builtins:

hasattr(obj, name, /)
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.

===========================================================================
34. hash()

Help on built-in function hash in module builtins:

hash(obj, /)
    Return the hash value for the given object.
    
    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.

===========================================================================
36. hex()

Help on built-in function hex in module builtins:

hex(number, /)
    Return the hexadecimal representation of an integer.
    
    >>> hex(12648430)
    '0xc0ffee'

===========================================================================
37. id()

Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.
    
    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)

===========================================================================
38. input()

Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

===========================================================================
40. isinstance()

Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.
    
    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.

===========================================================================
41. issubclass()

Help on built-in function issubclass in module builtins:

issubclass(cls, class_or_tuple, /)
    Return whether 'cls' is derived from another class or is the same class.
    
    A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
    or ...``.

===========================================================================
42. iter()

Help on built-in function iter in module builtins:

iter(...)
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator
    
    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.

===========================================================================
43. len()

Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

===========================================================================
46. locals()

Help on built-in function locals in module builtins:

locals()
    Return a dictionary containing the current scope's local variables.
    
    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.

===========================================================================
48. max()

Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.

===========================================================================
50. min()

Help on built-in function min in module builtins:

min(...)
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its smallest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the smallest argument.

===========================================================================
51. next()

Help on built-in function next in module builtins:

next(...)
    next(iterator[, default])
    
    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.

===========================================================================
53. oct()

Help on built-in function oct in module builtins:

oct(number, /)
    Return the octal representation of an integer.
    
    >>> oct(342391)
    '0o1234567'

===========================================================================
54. open()

Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.

    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)

===========================================================================
55. ord()

Help on built-in function ord in module builtins:

ord(c, /)
    Return the Unicode code point for a one-character string.

===========================================================================
56. pow()

Help on built-in function pow in module builtins:

pow(base, exp, mod=None)
    Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
    
    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.

===========================================================================
57. print()

Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.
    
    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
    file
      a file-like object (stream); defaults to the current sys.stdout.
    flush
      whether to forcibly flush the stream.

===========================================================================
61. repr()

Help on built-in function repr in module builtins:

repr(obj, /)
    Return the canonical string representation of the object.
    
    For many object types, including most builtins, eval(repr(obj)) == obj.

===========================================================================
63. round()

Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

===========================================================================
65. setattr()

Help on built-in function setattr in module builtins:

setattr(obj, name, value, /)
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''

===========================================================================
67. sorted()

Help on built-in function sorted in module builtins:

sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

===========================================================================
70. sum()

Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

===========================================================================
74. vars()

Help on built-in function vars in module builtins:

vars(...)
    vars([object]) -> dictionary
    
    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.

===========================================================================

Version2

    abs(x, /)
        Return the absolute value of the argument.

    aiter(async_iterable, /)
        Return an AsyncIterator for an AsyncIterable object.

    all(iterable, /)
        Return True if bool(x) is True for all values x in the iterable.

        If the iterable is empty, return True.

    anext(...)
        async anext(aiterator[, default])

        Return the next item from the async iterator.  If default is given and the async
        iterator is exhausted, it is returned instead of raising StopAsyncIteration.

    any(iterable, /)
        Return True if bool(x) is True for any x in the iterable.

        If the iterable is empty, return False.

    ascii(obj, /)
        Return an ASCII-only representation of an object.

        As repr(), return a string containing a printable representation of an
        object, but escape the non-ASCII characters in the string returned by
        repr() using \\x, \\u or \\U escapes. This generates a string similar
        to that returned by repr() in Python 2.

    bin(number, /)
        Return the binary representation of an integer.

        >>> bin(2796202)
        '0b1010101010101010101010'

    breakpoint(...)
        breakpoint(*args, **kws)

        Call sys.breakpointhook(*args, **kws).  sys.breakpointhook() must accept
        whatever arguments are passed.

        By default, this drops you into the pdb debugger.

    callable(obj, /)
        Return whether the object is callable (i.e., some kind of function).

        Note that classes are callable, as are instances of classes with a
        __call__() method.

    chr(i, /)
        Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

    compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-1)
        Compile source into a code object that can be executed by exec() or eval().

        The source code may represent a Python module, statement or expression.
        The filename will be used for run-time error messages.
        The mode must be 'exec' to compile a module, 'single' to compile a
        single (interactive) statement, or 'eval' to compile an expression.
        The flags argument, if present, controls which future statements influence
        the compilation of the code.
        The dont_inherit argument, if true, stops the compilation inheriting
        the effects of any future statements in effect in the code calling
        compile; if absent or false these statements do influence the compilation,
        in addition to any features explicitly specified.

    delattr(obj, name, /)
        Deletes the named attribute from the given object.

        delattr(x, 'y') is equivalent to ``del x.y``

    dir(...)
        Show attributes of an object.

        If called without an argument, return the names in the current scope.
        Else, return an alphabetized list of names comprising (some of) the attributes
        of the given object, and of attributes reachable from it.
        If the object supplies a method named __dir__, it will be used; otherwise
        the default dir() logic is used and returns:
          for a module object: the module's attributes.
          for a class object:  its attributes, and recursively the attributes
            of its bases.
          for any other object: its attributes, its class's attributes, and
            recursively the attributes of its class's base classes.

    divmod(x, y, /)
        Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.

    eval(source, globals=None, locals=None, /)
        Evaluate the given source in the context of globals and locals.

        The source may be a string representing a Python expression
        or a code object as returned by compile().
        The globals must be a dictionary and locals can be any mapping,
        defaulting to the current globals and locals.
        If only globals is given, locals defaults to it.

    exec(source, globals=None, locals=None, /, *, closure=None)
        Execute the given source in the context of globals and locals.

        The source may be a string representing one or more Python statements
        or a code object as returned by compile().
        The globals must be a dictionary and locals can be any mapping,
        defaulting to the current globals and locals.
        If only globals is given, locals defaults to it.
        The closure must be a tuple of cellvars, and can only be used
        when source is a code object requiring exactly that many cellvars.

    format(value, format_spec='', /)
        Return type(value).__format__(value, format_spec)

        Many built-in types implement format_spec according to the
        Format Specification Mini-language. See help('FORMATTING').

        If type(value) does not supply a method named __format__
        and format_spec is empty, then str(value) is returned.
        See also help('SPECIALMETHODS').

    getattr(...)
        Get a named attribute from an object.

        getattr(x, 'y') is equivalent to x.y
        When a default argument is given, it is returned when the attribute doesn't
        exist; without it, an exception is raised in that case.

    globals()
        Return the dictionary containing the current scope's global variables.

        NOTE: Updates to this dictionary *will* affect name lookups in the current
        global scope and vice-versa.

    hasattr(obj, name, /)
        Return whether the object has an attribute with the given name.

        This is done by calling getattr(obj, name) and catching AttributeError.

    hash(obj, /)
        Return the hash value for the given object.

        Two objects that compare equal must also have the same hash value, but the
        reverse is not necessarily true.

    hex(number, /)
        Return the hexadecimal representation of an integer.

        >>> hex(12648430)
        '0xc0ffee'

    id(obj, /)
        Return the identity of an object.

        This is guaranteed to be unique among simultaneously existing objects.
        (CPython uses the object's memory address.)

    input(prompt='', /)
        Read a string from standard input.  The trailing newline is stripped.

        The prompt string, if given, is printed to standard output without a
        trailing newline before reading input.

        If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
        On *nix systems, readline is used if available.

    isinstance(obj, class_or_tuple, /)
        Return whether an object is an instance of a class or of a subclass thereof.

        A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
        check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
        or ...`` etc.

    issubclass(cls, class_or_tuple, /)
        Return whether 'cls' is derived from another class or is the same class.

        A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
        check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
        or ...``.

    iter(...)
        Get an iterator from an object.

        In the first form, the argument must supply its own iterator, or be a sequence.
        In the second form, the callable is called until it returns the sentinel.

    len(obj, /)
        Return the number of items in a container.

    locals()
        Return a dictionary containing the current scope's local variables.

        NOTE: Whether or not updates to this dictionary will affect name lookups in
        the local scope and vice-versa is *implementation dependent* and not
        covered by any backwards compatibility guarantees.

    max(...)
        max(iterable, *[, default=obj, key=func]) -> value
        max(arg1, arg2, *args, *[, key=func]) -> value

        With a single iterable argument, return its biggest item. The
        default keyword-only argument specifies an object to return if
        the provided iterable is empty.
        With two or more arguments, return the largest argument.

    min(...)
        min(iterable, *[, default=obj, key=func]) -> value
        min(arg1, arg2, *args, *[, key=func]) -> value

        With a single iterable argument, return its smallest item. The
        default keyword-only argument specifies an object to return if
        the provided iterable is empty.
        With two or more arguments, return the smallest argument.

    next(...)
        Return the next item from the iterator.

        If default is given and the iterator is exhausted,
        it is returned instead of raising StopIteration.

    oct(number, /)
        Return the octal representation of an integer.

        >>> oct(342391)
        '0o1234567'

    open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
        Open file and return a stream.  Raise OSError upon failure.

        file is either a text or byte string giving the name (and the path
        if the file isn't in the current working directory) of the file to
        be opened or an integer file descriptor of the file to be
        wrapped. (If a file descriptor is given, it is closed when the
        returned I/O object is closed, unless closefd is set to False.)

        mode is an optional string that specifies the mode in which the file
        is opened. It defaults to 'r' which means open for reading in text
        mode.  Other common values are 'w' for writing (truncating the file if
        it already exists), 'x' for creating and writing to a new file, and
        'a' for appending (which on some Unix systems, means that all writes
        append to the end of the file regardless of the current seek position).
        In text mode, if encoding is not specified the encoding used is platform
        dependent: locale.getencoding() is called to get the current locale encoding.
        (For reading and writing raw bytes use binary mode and leave encoding
        unspecified.) The available modes are:

        ========= ===============================================================
        Character Meaning
        --------- ---------------------------------------------------------------
        'r'       open for reading (default)
        'w'       open for writing, truncating the file first
        'x'       create a new file and open it for writing
        'a'       open for writing, appending to the end of the file if it exists
        'b'       binary mode
        't'       text mode (default)
        '+'       open a disk file for updating (reading and writing)
        ========= ===============================================================

        The default mode is 'rt' (open for reading text). For binary random
        access, the mode 'w+b' opens and truncates the file to 0 bytes, while
        'r+b' opens the file without truncation. The 'x' mode implies 'w' and
        raises an `FileExistsError` if the file already exists.

        Python distinguishes between files opened in binary and text modes,
        even when the underlying operating system doesn't. Files opened in
        binary mode (appending 'b' to the mode argument) return contents as
        bytes objects without any decoding. In text mode (the default, or when
        't' is appended to the mode argument), the contents of the file are
        returned as strings, the bytes having been first decoded using a
        platform-dependent encoding or using the specified encoding if given.

        buffering is an optional integer used to set the buffering policy.
        Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
        line buffering (only usable in text mode), and an integer > 1 to indicate
        the size of a fixed-size chunk buffer.  When no buffering argument is
        given, the default buffering policy works as follows:

        * Binary files are buffered in fixed-size chunks; the size of the buffer
          is chosen using a heuristic trying to determine the underlying device's
          "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
          On many systems, the buffer will typically be 4096 or 8192 bytes long.

        * "Interactive" text files (files for which isatty() returns True)
          use line buffering.  Other text files use the policy described above
          for binary files.

        encoding is the name of the encoding used to decode or encode the
        file. This should only be used in text mode. The default encoding is
        platform dependent, but any encoding supported by Python can be
        passed.  See the codecs module for the list of supported encodings.

        errors is an optional string that specifies how encoding errors are to
        be handled---this argument should not be used in binary mode. Pass
        'strict' to raise a ValueError exception if there is an encoding error
        (the default of None has the same effect), or pass 'ignore' to ignore
        errors. (Note that ignoring encoding errors can lead to data loss.)
        See the documentation for codecs.register or run 'help(codecs.Codec)'
        for a list of the permitted encoding error strings.

        newline controls how universal newlines works (it only applies to text
        mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
        follows:

        * On input, if newline is None, universal newlines mode is
          enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
          these are translated into '\n' before being returned to the
          caller. If it is '', universal newline mode is enabled, but line
          endings are returned to the caller untranslated. If it has any of
          the other legal values, input lines are only terminated by the given
          string, and the line ending is returned to the caller untranslated.

        * On output, if newline is None, any '\n' characters written are
          translated to the system default line separator, os.linesep. If
          newline is '' or '\n', no translation takes place. If newline is any
          of the other legal values, any '\n' characters written are translated
          to the given string.

        If closefd is False, the underlying file descriptor will be kept open
        when the file is closed. This does not work when a file name is given
        and must be True in that case.

        A custom opener can be used by passing a callable as *opener*. The
        underlying file descriptor for the file object is then obtained by
        calling *opener* with (*file*, *flags*). *opener* must return an open
        file descriptor (passing os.open as *opener* results in functionality
        similar to passing None).

        open() returns a file object whose type depends on the mode, and
        through which the standard file operations such as reading and writing
        are performed. When open() is used to open a file in a text mode ('w',
        'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
        a file in a binary mode, the returned class varies: in read binary
        mode, it returns a BufferedReader; in write binary and append binary
        modes, it returns a BufferedWriter, and in read/write mode, it returns
        a BufferedRandom.

        It is also possible to use a string or bytearray as a file for both
        reading and writing. For strings StringIO can be used like a file
        opened in a text mode, and for bytes a BytesIO can be used like a file
        opened in a binary mode.

    ord(c, /)
        Return the Unicode code point for a one-character string.

    pow(base, exp, mod=None)
        Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments

        Some types, such as ints, are able to use a more efficient algorithm when
        invoked using the three argument form.

    print(*args, sep=' ', end='\n', file=None, flush=False)
        Prints the values to a stream, or to sys.stdout by default.

        sep
          string inserted between values, default a space.
        end
          string appended after the last value, default a newline.
        file
          a file-like object (stream); defaults to the current sys.stdout.
        flush
          whether to forcibly flush the stream.

    repr(obj, /)
        Return the canonical string representation of the object.

        For many object types, including most builtins, eval(repr(obj)) == obj.

    round(number, ndigits=None)
        Round a number to a given precision in decimal digits.

        The return value is an integer if ndigits is omitted or None.  Otherwise
        the return value has the same type as the number.  ndigits may be negative.

    setattr(obj, name, value, /)
        Sets the named attribute on the given object to the specified value.

        setattr(x, 'y', v) is equivalent to ``x.y = v``

    sorted(iterable, /, *, key=None, reverse=False)
        Return a new list containing all items from the iterable in ascending order.

        A custom key function can be supplied to customize the sort order, and the
        reverse flag can be set to request the result in descending order.

    sum(iterable, /, start=0)
        Return the sum of a 'start' value (default: 0) plus an iterable of numbers

        When the iterable is empty, return the start value.
        This function is intended specifically for use with numeric values and may
        reject non-numeric types.

    vars(...)
        Show vars.

        Without arguments, equivalent to locals().
        With an argument, equivalent to object.__dict__.


1. key参数的巧用

除了sorted()函数有key参数,max,min函数也有,不要以为max,min只能用来比大小。

lst = ['abcd','abc','abcde','ab']
print(max(lst, key=len))
print(min(lst, key=len))

string = 'bcdABCxyzwl'                                                    
print(max(string, key=ord))
print(min(string, key=ord))

data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}, {'name': 'Charlie', 'age': 23}]  
oldest_person = max(data, key=lambda x: x['age'])
youngest_person = min(data, key=lambda x: x['age'])
print(oldest_person)
print(youngest_person)

2. sum()函数的巧用

也不要以为sum只能用来合计数的大小,它可以用来合并或降维列表。

>>> lst1 = [1,2,3]
>>> lst2 = [4,5]
>>> lst3 = [6,7,8]
>>> lst = sum([lst1,lst2,lst3], [])
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8]


>>> lst = [[1,2,3], [4,5], [6,7,8]]
>>> sum(lst, [])
[1, 2, 3, 4, 5, 6, 7, 8]

目录

built-in function

Version1

Version2

1. key参数的巧用

2. sum()函数的巧用


完 

  • 43
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值