Python: Built in Functions md - chiun/python-syntax-pretty-docs GitHub Wiki
For 3.6
https://docs.python.org/3/library/functions.html
Summary
Math
Function | Description |
---|---|
abs() | Returns absolute value of a number |
divmod() | Returns quotient and remainder of integer division |
max() | Returns the largest of the given arguments or items in an iterable |
min() | Returns the smallest of the given arguments or items in an iterable |
pow() | Raises a number to a power |
round() | Rounds a floating-point value |
sum() | Sums the items of an iterable |
Type Conversion
Function | Description |
---|---|
ascii() | Returns a string containing a printable representation of an object |
bin() | Converts an integer to a binary string |
bool() | Converts an argument to a Boolean value |
chr() | Returns string representation of character given by integer argument |
complex() | Returns a complex number constructed from arguments |
float() | Returns a floating-point object constructed from a number or string |
hex() | Converts an integer to a hexadecimal string |
int() | Returns an integer object constructed from a number or string |
oct() | Converts an integer to an octal string |
ord() | Returns integer representation of a character |
repr() | Returns a string containing a printable representation of an object |
str() | Returns a string version of an object |
type() | Returns the type of an object or creates a new type object |
Iterables and Iterators
Function | Description |
---|---|
all() | Returns True if all elements of an iterable are true |
any() | Returns True if any elements of an iterable are true |
enumerate() | Returns a list of tuples containing indices and values from an iterable |
filter() | Filters elements from an iterable |
iter() | Returns an iterator object |
len() | Returns the length of an object |
map() | Applies a function to every item of an iterable |
next() | Retrieves the next item from an iterator |
range() | Generates a range of integer values |
reversed() | Returns a reverse iterator |
slice() | Returns a slice object |
sorted() | Returns a sorted list from an iterable |
zip() | Creates an iterator that aggregates elements from iterables |
Composite Data Type
Function | Description |
---|---|
bytearray() | Creates and returns an object of the bytearray class |
bytes() | Creates and returns a bytes object (similar to bytearray, but immutable) |
dict() | Creates a dict object |
frozenset() | Creates a frozenset object |
list() | Constructs a list object |
object() | Returns a new featureless object |
set() | Creates a set object |
tuple() | Creates a tuple object |
Classes, Attributes, and Inheritance
Function | Description |
---|---|
classmethod() | Returns a class method for a function |
delattr() | Deletes an attribute from an object |
getattr() | Returns the value of a named attribute of an object |
hasattr() | Returns True if an object has a given attribute |
isinstance() | Determines whether an object is an instance of a given class |
issubclass() | Determines whether a class is a subclass of a given class |
property() | Returns a property value of a class |
setattr() | Sets the value of a named attribute of an object |
super() | Returns a proxy object that delegates method calls to a parent or sibling class |
Input/Output
Function | Description |
---|---|
format() | Converts a value to a formatted representation |
input() | Reads input from the console |
open() | Opens a file and returns a file object |
print() | Prints to a text stream or the console |
Variables, References, and Scope
Function | Description |
---|---|
dir() | Returns a list of names in current local scope or a list of object attributes |
globals() | Returns a dictionary representing the current global symbol table |
id() | Returns the identity of an object |
locals() | Updates and returns a dictionary representing current local symbol table |
vars() | Returns dict attribute for a module, class, or object |
Miscellaneous
Function | Description |
---|---|
callable() | Returns True if object appears callable |
compile() | Compiles source into a code or AST object |
eval() | Evaluates a Python expression |
exec() | Implements dynamic execution of Python code |
hash() | Returns the hash value of an object |
help() | Invokes the built-in help system |
memoryview() | Returns a memory view object |
staticmethod() | Returns a static method for a function |
import() | Invoked by the import statement |
Descriptions
Dealing with iterables and collections
Return True if all elements of the iterable are true (or if the iterable is empty).
Return True if any element of the iterable is true. If the iterable is empty, return False.
class bytearray ([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. The optional source parameter can be used to initialize the array in a few different ways …
class dict (iterable, **kwarg)
Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class. For other containers see the built-in list, set, and tuple classes, as well as the collections module.
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
Construct an iterator from those elements of iterable for which function returns true. Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.
Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned. See also Iterator Types. One useful application of the second form of iter() is to read lines of a file until a certain line is reached.
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().
max (iterable, *[, key, default])
max (arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments. The key argument specifies a one-argument ordering function like that used for list.sort()
min (iterable, *[, key, default])
min (arg1, arg2, *args[, key])
Return the smallest item in an iterable or the smallest of two or more arguments.
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.
Return a reverse iterator. seq must be an object which has a reversed() method or supports the sequence protocol (the len() method and the getitem() method with integer arguments starting at 0).
sorted (iterable, *, key=None, reverse=False)
Return a new sorted list from the items in iterable. key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
class slice (start, stop[, step])
Return a slice object representing the set of indices specified by range(start, stop, step). Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable’s items are normally numbers, and the start value is not allowed to be a string.
Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.
Make an iterator that aggregates elements from each of the iterables. Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. x2, y2 = zip(*zip(x, y)) - zip-unzip (all args are lists)
Objects in general
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.
Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure.
Return True if the object argument appears callable, False if not.
Transform a method into a class method (almost like static method). A class method receives the class as implicit first argument, just like an instance method receives the instance. Decorator!!!
This is a relative of setattr(). The function deletes the named attribute. For example, delattr(x, 'foobar') is equivalent to del x.foobar.
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.
getattr (object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent tox.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)
Return the hash value of the object (if it has one). Hash values are integers.
Invoke the built-in help system. (This function is intended for interactive use.)
- no argument is given: the interactive help system starts on the interpreter console.
- argument is a string: then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console.
- argument is any other kind of object: a help page on the object is generated.
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
isinstance (object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
Return true if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
Note
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
Return a “memory view” object created from the given argument. See Memory Views for more information.
Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.
Note
object does not have a dict, so you can’t assign arbitrary attributes to an instance of the object class.
class property(fget=None, fset=None, fdel=None, doc=None)
Return a property attribute. 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. And doc creates a docstring for the attribute.
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
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.” A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
class set ([iterable]) Return a new set object, optionally with elements taken from iterable.
This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.
Return a static method for function.
class str(object=b”, encoding=’utf-8’, errors=’strict’)
Return a str version of object. See str() for details.
super ([type[, object-or-type]])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr()except that the type itself is skipped. For practical suggestions on how to design cooperative classes using super(), see guide to using super().
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__. The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account. With three arguments, return a new type object.
Return the dict attribute for a module, class, instance, or any other object with a dict attribute.
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Note
This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module(). This function is invoked by the import statement.
Input-output
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
print (*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments. All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end. The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.
Numeric functions
Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.
Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer.
class bytes([source[, encoding[, errors]]])
Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray
Return a complex number with the value real + imag*1j or convert a string or number to a complex number.
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division.
Return a floating point number constructed from a number or string x. Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.
Convert an integer number to a lowercase hexadecimal string prefixed with “0x”.
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.int(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8). The integer type is described in Numeric Types — int, float, complex. Changed in version 3.4: If base is not an instance of int and the base object has a base.index method, that method is called to obtain an integer for the base. Previous versions used base.int instead of base.index. Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.
Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer. For example:
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). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
Other
Return the string representing a character whose Unicode code point is the integer i.
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Compile the source into a code or AST object. Refer to the ast module documentation for information on how to work with AST objects.
eval(expression, globals=None, locals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
exec(object[, globals[, locals]])
This function supports dynamic execution of Python code.