List of Python Built-in Functions and Exceptions

python functions techhyme

All built-in names (functions, exceptions, and so on) exist in the implied outer built-in scope, which corresponds to the _ _builtin_ _ module. Because this scope is always searched last on name lookups, these functions are always available in programs without imports.

Also Read: [Free Download] 200+ Python Books For Beginners and Experts (2022 Update)

However, their names are not reserved words and may be hidden by assignments to the same name in global or local scopes.

  1. abs(N)
    Returns the absolute value of a number N.
  2. apply(func, args [, keys])
    Calls any callable object func (a function, method, class, etc.), passing the positional arguments in tuple args, and the keyword arguments in dictionary keys. Returns func call result.
  3. buffer(object [, offset [, size]])
    Returns a new buffer object for a conforming object.
  4. callable(object)
    Returns 1 if object is callable; else, returns 0.
  5. chr(Int)
    Returns a one-character string whose ASCII code is integer Int.
  6. cmp(X, Y)
    Returns a negative integer, zero, or a positive integer to designate (X < Y), (X == Y), or (X > Y), respectively.
  7. coerce(X, Y)
    Returns a tuple containing the two numeric arguments X and Y converted to a common type.
  8. compile(string, filename, kind)
    Compiles string into a code object. string is a Python string containing Python program code. filename is a string used in error messages (and is usually the name of the file from which the code was read, or if typed interactively). kind can be exec if string contains statements; eval if string is an expression; or single, which prints the output of an expression statement that evaluates to something other than None. The resulting code object can be executed with exec statements or eval calls.
  9. complex(real [, imag])
    Builds a complex number object (can also be done using J or j suffix: real+imagJ). imag defaults to 0.
  10. delattr(object, name)
    Deletes the attribute named name (a string) from object. Similar to del obj.name, but name is a string, not a variable (e.g., delattr(a,’b’) is like del a.b).
  11. dir([object])
    If no arguments, returns the list of names in the current local scope (namespace). With any object with attributes as an argument, returns the list of attribute names associated with that object. In 1.5 and later, works on modules, classes, and class instances, as well as built-in objects with attributes (lists, dictionaries, etc.).
  12. divmod(X, Y)
    Returns a tuple of (X / Y, X % Y).
  13. eval(expr [, globals [, locals]])
    Evaluates expr, which is assumed to be either a Python string containing a Python expression or a compiled code object. expr is evaluated in the namespaces of the eval call unless the globals and/or locals namespace dictionary arguments are passed. locals defaults to globals if only globals is passed. Returns expr result.
  14. execfile(filename [, globals [, locals]])
    Like eval, but runs all the code in a file whose string name is passed in as filename (instead of an expression). Unlike imports, does not create a new module object for the file. Returns None. Namespaces for code in filename are as for eval.
  15. filter(function, sequence)
    Constructs a list from those elements of sequence for which function returns true. function takes one parameter. If function is None, returns all true items.
  16. float(X)
    Converts a number or a string X to a floating-point number.
  17. getattr(object, name [, default])
    Returns the value of attribute name (a string) from object. Similar to object.name, but name is a string, not a variable (e.g., getattr(a,’b’) is like a.b). If the named attribute does not exist, default is returned if provided; otherwise, AttributeError is raised.
  18. globals( )
    Returns a dictionary containing the caller’s global variables (e.g., the enclosing module’s names).
  19. hasattr(object, name)
    Returns true if object has an attribute called name (a string); false otherwise.
  20. hash(object)
    Returns the hash value of object (if it has one).
  21. hex(N)
    Converts a number N to a hexadecimal string.
  22. id(object)
    Returns the unique identity integer of object (i.e., its address in memory).
  23. _ _import_ _(name [,globals [,locals [, fromlist] ]])
    Imports and returns a module, given its name as a string, not a variable (e.g., mod = _ _import_ _(“mymod”)). Generally faster than constructing and executing an import statement string with exec. This function is called by import and from statements and may be overriden to customize import operations.
  24. input([prompt])
    Prints prompt, if given. Then reads an input line from the stdin stream (sys.stdin), evaluates it as Python code, and returns the result. Like eval(raw_input(prompt)).
  25. int(X [, base])
    Converts a number or a string X to a plain integer. base may be passed only if X is a string; if base is passed as 0, the base is determined by the string contents; else, the value passed for base is used for the base of the conversion. Conversion of floating-point numbers to integers truncates toward 0.
  26. intern(string)
    Enter string in the table of “interned strings” and return the interned string. Interned strings are “immortals” and serve as a performance optimization (they may be compared by fast is identity, rather than == equality).
  27. isinstance(object, classOrType)
    Returns true if object is an instance of classOrType, or an instance of any subclass thereof.
  28. issubclass(class1, class2)
    Returns true if class1 is derived from class2.
  29. iter(object [, sentinel])
    Returns an iterator object that may be used to step through items in object. Iterator objects returned have a next( ) method that returns the next item or raises StopIteration to end the progression. If one argument, object is assumed to provide its own iterator or be a sequence (normal case); if two arguments, object is a callable that is called until it returns sentinel. May overload in classes with _ _iter_ _; may be automatically called by Python in all iteration contexts.
  30. len(object)
    Returns the number of items (length) in a collection object. Works on sequences and mappings.
  31. list(sequence)
    Converter: returns a new list containing all the items in any sequence object. If sequence is already a list, returns a copy of it.
  32. locals( )
    Returns a dictionary containing the local variables of the caller (with one key:value entry per local).
  33. long(X [, base])
    Converts a number or a string X to a long integer. base may be passed only if X is a string. If 0, the base is determined by the string contents; else, it is used for the base of the conversion.
  34. map(function, seq [, seq]*)
    Applies function to every item of any sequence seq and returns a list of the collected results. Example: map(abs, (1, -2)) returns [1, 2]. If additional sequence arguments are passed, function must take that many arguments, and it is passed one item from each sequence on every call. If function is None, map collects all the items into a result list. If sequences differ in length, all are padded to length of longest, with Nones.
  35. max(S [, arg]*)
    With a single argument S, returns largest item of a nonempty sequence (e.g., string, tuple, list). With more than one argument, returns largest of the arguments.
  36. min(S [, arg]*)
    With a single argument S, returns smallest item of a nonempty sequence (e.g., string, tuple, list). With more than one argument, returns smallest of the arguments.
  37. oct(N)
    Converts a number N to an octal string.
  38. open(filename [, mode, [bufsize]])
    Returns a new file object, connected to the external file named filename (a string). The filename is mapped to the current working directory, unless the filename string includes a directory prefix. The first two arguments are the same as those for C’s stdio fopen function, and the file is managed by the “stdio” system.
    mode defaults to ‘r’ if omitted, but can be ‘r’ for input; ‘w’ for output; ‘a’ for append; and ‘rb’, ‘wb’, or ‘ab’ for binary files (to suppress line-end conversions). On most systems, most of these can also have a “+” appended to open in input/output updates mode (e.g., ‘r+’).
    bufsize defaults to an implementation-dependent value, but can be 0 for unbuffered, 1 for line-buffered, negative for system-default, or a given specific size. Buffered data transfers may not be immediately fulfilled (use flush methods to force).
  39. ord(C)
    Returns integer ASCII value of a one-character string C (or the Unicode code point, if C is a one-character Unicode string).
  40. pow(X, Y [, Z])
    Returns X to power Y [modulo Z]. Similar to the ** expression operator.
  41. range([start,] stop [, step])
    Returns a list of successive integers between start and stop. With one argument, returns integers from zero through stop-1. With two arguments, returns integers from start through stop-1. With three arguments, returns integers from start through stop-1, adding step to each predecessor in the result. start, step default to 0, 1. range(0,20,2) is a list of even integers from 0 through 18. Often used to generate offset lists for for loops.
  42. raw_input([prompt])
    Prints prompt string if given, then reads a line from the stdin input stream (sys.stdin) and returns it as a string. Strips trailing \n at end of line and raises EOFError at the end of the stdin stream.
  43. reduce(func, list [, init])
    Applies the two-argument function func to successive items from list, so as to reduce the list to a single value. If init is given, it is prepended to list.
  44. reload(module)
    Reloads, re-parses, and re-executes an already imported module in the module’s current namespace. Re-execution replaces prior values of the module’s attributes in-place. module must reference an existing module object; it is not a new name or a string. Useful in interactive mode if you want to reload a module after fixing it, without restarting Python. Returns the module object.
  45. repr(object)
    Returns a string containing a printable, and potentially parseable, representation of any object. Equivalent to `object` (backquotes expression).
  46. round(X [, N])
    Returns the floating-point value X rounded to N digits after the decimal point. N defaults to zero.
  47. setattr(object, name, value)
    Assigns value to attribute name (a string) in object. Like object.name = value, but name is a string, not a variable name (e.g., setattr(a,’b’,c) is like a.b=c).
  48. slice([start ,] stop [, step])
    Returns a slice object representing a range, with read-only attributes start, stop, and step, any of which may be None. Arguments are the same as for range.
  49. str(object)
    Returns a string containing the printable representation of object.
  50. tuple(sequence)
    Converter: returns a new tuple with the same elements as any sequence passed in. If sequence is already a tuple, it is returned directly (not a copy).
  51. type(object)
    Returns a type object representing the type of object. Useful for type-testing in if statements (e.g., if type(X)==type([]):).
  52. unichr(i)
    Returns the Unicode string of one character whose Unicode code is the integer i (e.g., unichr(97) returns the string u’a’). This is the inverse of ord for Unicode strings. Argument must be in range 0..65535 inclusive, or ValueError is raised.
  53. unicode(string [, encoding [, errors]])
    Decodes string using the codec for encoding. Error handling is done according to errors. The default behavior is to decode UTF-8 in strict mode, meaning that encoding errors raise ValueError.
  54. vars([object])
    Without arguments, returns a dictionary containing the current local scope’s names. With a module, class, or class instance object as an argument, returns a dictionary corresponding to object’s attribute namespace (i.e., its _ _dict_ _). Useful for “%” string formatting.
  55. xrange([start,] stop [, step])
    Like range, but doesn’t actually store entire list all at once (generates one integer at a time). Good to use in for loops when there is a big range and little memory. Optimizes space, but generally has no speed benefit.
  56. zip(seq [, seq]*)
    Returns a list of tuples, where each ith tuple contains the ith element from each of the argument sequences seq. For example, zip(‘ab’, ‘cd’) returns [(‘a’, ‘c’), (‘b’, ‘d’)]. At least one sequence is required, or a TypeError is raised. The result list is truncated to the length of the shortest argument sequence. When there are multiple argument sequences of the same length, zip is similar to map with a first argument of None. With a single sequence argument, it returns a list of one-tuples.

Built-in Exceptions

Beginning with Python 1.5, all built-in exceptions are class objects. Prior to 1.5, they were strings. Class exceptions are mostly indistinguishable from strings, unless they are concatenated. Built-in exceptions are defined in the module exceptions; this module never needs to be imported explicitly, because the exception names are provided in the built-in scope namespace. Most built-in exceptions have an associated extra data value with details.

Base Classes (Categories)

  1. Exception
    Root superclass for all exceptions. User-defined exceptions may be derived from this class, but this is not currently enforced or required.
  2. StandardError
    Superclass for all other built-in exceptions except for SystemExit; subclass of the Exception root class.
  3. ArithmeticError
    Superclass for OverflowError, ZeroDivisionError, FloatingPointError; subclass of StandardError.
  4. LookupError
    Superclass for IndexError, KeyError; subclass of StandardError.
  5. EnvironmentError
    Superclass for exceptions that occur outside Python (IOError, OSError); subclass of StandardError.

Specific Exceptions Raised

  1. AssertionError
    When an assert statement’s test is false.
  2. AttributeError
    On attribute reference or assignment failure.
  3. EOFError
    When immediate end of file is hit by input( ) or raw_input( ).
  4. FloatingPointError
    On floating-point operation failure.
  5. IOError
    On I/O or file-related operation failure.
  6. ImportError
    On failure of import to find module or attribute.
  7. IndexError
    On out-of-range sequence offset (fetch or assign).
  8. KeyError
    On reference to nonexistent mapping key (fetch).
  9. KeyboardInterrupt
    On user entry of the interrupt key (often Ctrl-C).
  10. MemoryError
    On recoverable memory exhaustion.
  11. NameError
    On failure to find a local or global unqualified name.
  12. NotImplementedError
    On failure to define expected protocols. New in 1.5.2.
  13. OSError
    On os module error (its os.error exception). New in 1.5.2.
  14. OverflowError
    On excessively large arithmetic operation.
  15. RuntimeError
    Rarely used catch-all.
  16. StopIteration
    On end of progression in iterator objects. New in 2.2.
  17. SyntaxError
    On parser encountering a syntax error.
  18. SystemError
    On interpreter internal error (a bug—report it).
  19. SystemExit
    On a call to sys.exit( ) (can trap and ignore).
  20. TypeError
    On passing inappropriate type to built-in operation.
  21. UnboundLocalError
    On reference to local name that has not been assigned. New in 2.0.
  22. UnicodeError
    On Unicode-related encoding or decoding error. New in 2.0.
  23. ValueError
    On argument errors not covered by TypeError or other.
  24. WindowsError
    On Windows-specific errors. New in 2.0.
  25. ZeroDivisionError
    On division or modulus operation with 0 on the right.

Warning category exceptions

The following exceptions are used as warning categories:

  1. Warning
    Base class for all warning categories below, subclass of Exception.
  2. UserWarning
    Base class for warnings generated by user code.
  3. DeprecationWarning
    Base class for warnings about deprecated features.
  4. SyntaxWarning
    Base class for warnings about dubious syntax.
  5. RuntimeWarning
    Base class for warnings about dubious runtime behavior.
You may also like:

Related Posts