Built-in classes and functions

The classes and functions shown on this page can be used without importing anything.

Input and output

input() str
input(prompt) str

Gets input from the user in the terminal window. It waits until the user presses Enter.

Parameters

prompt (str) – If given, this is printed in the terminal window first. This can be used to ask a question so the user knows what to type.

Returns

Everything the user typed before pressing Enter.

print(*objects, sep=' ', end='\n', file=usys.stdin)

Prints text or other objects in the terminal window.

Parameters

objects – Zero or more objects to print.

Keyword Arguments
  • sep – This is printed between objects, if there is more than one.

  • end – This is printed after the last object.

  • file – By default, the result is printed in the terminal window. This argument lets you print it to a file instead, if files are supported.

Basic types

class bool()
class bool(x)

Creates a boolean value, which is either True or False.

The input value is converted using the standard truth testing procedure. If no input is given, it is assumed to be False.

Parameters

x – Value to be converted.

Returns

Result of the truth-test.

class complex(string)
class complex(a=0, b=0)

Creates a complex number from a string or from a pair of numbers.

If a string is given, it must be of the form '1+2j'. If a pair of numbers is provided, the result is computed as: a + b * j.

Parameters
  • string (str) – A string of the form '1+2j' .

  • a (float or complex) – A real-valued or complex number.

  • b (float or complex) – A real-valued or complex number.

Returns

The resulting complex number.

class dict(**kwargs)
class dict(mapping, **kwargs)
class dict(iterable, **kwargs)

See the standard Python documentation for a comprehensive reference with examples.

class float(x=0.0)

Creates a floating point number from a given object.

Parameters

x (int or float or str) – Number or string to be converted.

class int(x=0)

Creates an integer.

Parameters

x (int or float or str) – Object to be converted.

to_bytes(length, byteorder) bytes

Get a bytes representation of the integer.

Parameters
  • length (int) – How many bytes to use.

  • byteorder (str) – Choose "big" to put the most significant byte first. Choose "little" to put the least significant byte first.

Returns

Byte sequence that represents the integer.

classmethod from_bytes(bytes, byteorder) int

Convert a byte sequence to the number it represents.

Parameters
  • bytes (bytes) – The bytes to convert.

  • byteorder (str) – Choose "big" if the most significant byte is the first element. Choose "little" if the least significant byte is the first element.

Returns

The number represented by the bytes.

class object

Return a new featureless object.

class type(object: Any)

With one argument, returns the type of an object.

Sequences

class bytearray
class bytearray(source: int)
class bytearray(source: Union[bytes, bytearray, str, Iterable[int]])

Creates a new bytearray object, which is a sequence of integers in the range \(0 \leq x \leq 255\). This object is mutable, which means that you can change its contents after you create it.

  • If no argument is given, this creates an empty bytearray.

  • If the source argument is an integer, this creates a bytearray of zeros. The argument specifies how many zeros.

  • For all other valid source arguments, this creates a bytearray with the same byte sequence as the given source argument.

class bytes
class bytes(source: int)
class bytes(source: Union[bytes, bytearray, Iterable[int]])
class bytes(source: str, encoding: str)

Creates a new bytes object, which is a sequence of integers in the range \(0 \leq x \leq 255\). This object is immutable, which means that you cannot change its contents after you create it.

  • If no argument is given, this creates an empty bytes object.

  • If the source argument is an integer, this creates a bytes object of zeros. The argument specifies how many zeros.

  • If source is a bytearray, bytes object, or some other iterable of integers, this creates a bytes object with the same byte sequence as the source argument.

  • If source is a string, choose 'utf8' as the encoding argument. Then this creates a bytes object containing the encoded string.

len(s: Sequence) int

Returns the length (the number of items) of an object.

class list
class list(iterable: Iterable)

Creates a new list.

class slice(stop: int)
class slice(start: int, stop: int)
class slice(start: int, stop: int, step: int)

Returns 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].

class str(object: Any = '')
class str(object: bytes = b'', encoding: str = 'utf-8', errors: str = 'strict')

Return a str version of object.

class tuple
class tuple(iterable: Iterable)

Rather than being a function, tuple is actually an immutable sequence type.

Iterators

all(x) bool

Checks if all elements of the iterable are true.

Equivalent to:

def all(x):
    for element in x:
        if not element:
            return False
    return True
Parameters

x (Iterable) – The iterable to be checked.

Returns

True if the iterable x is empty or if all elements are true. Otherwise False.

any(x) bool

Checks if at least one elements of the iterable is true.

Equivalent to:

def any(x):
    for element in x:
        if element:
            return True
    return False
Parameters

x (Iterable) – The iterable to be checked.

Returns

True if at least one element in x is true. Otherwise False.

class enumerate(iterable: Iterable)
class enumerate(iterable: Iterable, start: int)

Returns an enumerate object.

Equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
iter(object: Union[Iterable, Sequence]) Iterator

Returns an iterator object.

map(function: Callable, iterable: Iterable, *args: Any) Iterator

Returns an iterator that applies function to every item of iterable, yielding the results.

next(iterator: Iterator) Any
next(iterator: Iterator, default: Any) Any

Retrieves 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.

class range(stop: int)
class range(start: int, stop: int)
class range(start: int, stop: int, step: int)

Rather than being a function, range is actually an immutable sequence type.

reversed(seq: Sequence) Iterator

Returns a reverse iterator.

sorted(iterable: Iterable, key=None, reverse=False) List

Returns a new sorted list from the items in iterable.

zip(*iterables: Iterable) Iterable[Tuple]

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.

Equivalent to:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

Conversion functions

bin(x) str

Converts an integer to its binary representation. The result is a string prefixed with 0b. The result is a valid Python expression. For example, bin(5) gives "0b101".

Parameters

x (int) – Value to be converted.

Returns

A string representing the binary form of the input.

chr(x) str

Returns the string representing a character whose Unicode code is the integer x. This is the inverse of ord(). For example, chr(97) gives "a".

Parameters

x (int) – Value to be converted (0-255).

Returns

A string with one character, corresponding to the given Unicode value.

hex(x) str

Converts an integer to its hexadecimal representation. The result is a lowercase string prefixed with 0x. The result is a valid Python expression. For example, hex(25) gives "0x19".

Parameters

x (int) – Value to be converted.

Returns

A string representing the hexadecimal form of the input.

oct(x) str

Converts an integer to its octal representation. The result is a string prefixed with 0o. The result is a valid Python expression. For example, oct(25) gives "0o31".

Parameters

x (int) – Value to be converted.

Returns

A string representing the octal form of the input.

ord(c) int

Converts a string consisting of one Unicode character to the corresponding number. This is the inverse of chr().

Parameters

c (str) – Character to be converted.

Returns

Number that represents the character (0–255).

repr(object) str

Gets the string that represents an object.

Parameters

x (object) – Object to be converted.

Returns

String representation implemented by the object’s __repr__ method.

Math functions

See also umath for floating point math operations.

abs(x) Any

Returns the absolute value of a number.

The argument may be an integer, a floating point number, or any object implementing __abs__(). If the argument is a complex number, its magnitude is returned.

Parameters

x (Any) – The value.

Returns

Absolute value of x.

divmod(a: int, b: int) Tuple[int, int]
divmod(a: float, b: float) Tuple[float, float]

Takes two (non complex) numbers as arguments and returns a pair of numbers consisting of their quotient and remainder when using integer division.

max(iterable: Iterable) Any
max(arg1: Any, arg2: Any, *args: Any) Any

Returns the largest item in an iterable or the largest of two or more arguments.

min(iterable: Iterable) Any
min(arg1: Any, arg2: Any, *args: Any) Any

Returns the smallest item in an iterable or the smallest of two or more arguments.

pow(base: int, exp: int) Union[int, float]
pow(base: int, exp: int, mod: int) Union[int, float]

Returns base to the power exp; if mod is present, returns base to the power exp, modulo mod.

The two-argument form pow(base, exp) is equivalent to using the power operator: base ** exp.

round(number: float) int
round(number: float, ndigits: int) float

Returns number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Tip

To print a number use a format function instead. Since many floating point numbers don’t have exact representations, round() often gives unexpected results!

Example:

# print two decimal places
print('my number: %.2f' % number)
print('my number: {:.2f}'.format(number))
sum(iterable: Iterable) int
sum(iterable: Iterable, start: int) int

Sums start and the items of an iterable from left to right and returns the total.

Runtime functions

eval(expression: str) Any
eval(expression: str, globals: dict) Any
eval(expression: str, globals: dict, locals: Mapping) Any

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.

The return value is the result of the evaluated expression. Syntax errors are reported as exceptions.

exec(object: Any) None
exec(object: Any, globals: dict) None
exec(object: Any, globals: dict, locals: Mapping) None

This function supports dynamic execution of Python code.

globals() Dict[str, Any]

Return a dictionary representing the current global symbol table.

hash(object: Any) int

Returns the hash value of the object (if it has one).

help() None
help(object: Any) None

Prints help for the object. If no argument is given, prints general help. If object is 'modules', prints available modules.

id() int

Returns the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime.

locals() dict

Updates and returns a dictionary representing the current local symbol table.

Class functions

callable(object: Any) bool

Returns True if the object argument appears callable, False if not.

dir() List[str]
dir(object: Any) List[str]

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.

getattr(object: Any, name: str) Any
getattr(object: Any, name: str, default: Any) Any

Returns the value of the named attribute of object.

hasattr(object: Any, name: str) bool

The result is True if the string is the name of one of the object’s attributes, False if not.

isinstance(object: Any, classinfo: Union[type, Tuple[type]]) bool

Returns True if the object argument is an instance of the classinfo argument, or of a subclass thereof.

issubclass(cls: type, classinfo: Union[type, Tuple[type]]) bool

Returns True if cls is a subclass of classinfo.

setattr(object: Any, name: str, value: Any) None

Assigns the value to the attribute, provided the object allows it.

This is the counterpart of getattr().

super() type
super(type: type) type
super(type: type, object_or_type: Any) type

Returns am object that delegates method calls to a parent or sibling class of type.

Method decorators

@classmethod

Transforms a method into a class method.

@staticmethod

Transforms a method into a static method.