Built-in functions

Quick Jump List

A: abs, aiter, all, anext, any, ascii, B: bin, bool, breakpoint, bytearray, bytes, C: callable, chr, classmethod, compile, complex, D: delattr, dict, dir, divmod E: enumerate, eval, exec, F: filter, float, format, frozenset, G: getattr, globals, H: hasattr, hash, help, hex, I: id, input, int, isinstance, issubclass, iter, L: len, list, locals, M: map, max, memoryview, min, N: next, O: object, oct, open, ord, P: pow, print, property, R: range, repr, reversed, round, S: set, setattr, slice, sorted, staticmethod, str, sum, super, T: tuple, type, V: vars, Z: zip, _: __import__,

Motivation

The content of the built-in functions documentation

abs

abs returns the absolute value of a number, which means it removes any negative sign. The result is always a positive number or zero.

Example:

x = abs(5)
print(x)
y = abs(-3.2)
print(x-y)

Back

aiter

aiter is the asynchronous version of iter. This allows you to iterate over asynchronous data sources, such as streams, one item at a time in an asynchronous loop.

If this example looks intimidating, fear not! Asynchronous programming is a more advanced Python concept. You are unlikely to encounter this much in a lot of Python code.

Example:

import asyncio
from collections.abc import AsyncIterable

class AsyncRange(AsyncIterable):
  def __init__(self, start, end):
    self.start = start
    self.end = end

  async def __aiter__(self):
    for i in range(self.start, self.end):
       await asyncio.sleep(1)
       yield i

async def example():
  async for i in aiter(AsyncRange(1, 4)):
     print(i)

print(asyncio.run(example()))

Back

all

all returns True if all elements in something list-like (such as a list or tuple) are “truthy” or if the list is empty. If any element is false, it returns False.

Example:

print(all([True, True, True]))

print(all([True, False, True]))

print(all([1, 2, 3]))

print(all([]))

Back

anext

anext is the asynchronous version of next. If the iterator is exhausted, it can raise a StopAsyncIteration exception unless a default value is provided.

If this example looks intimidating, fear not! Asynchronous programming is a more advanced Python concept. You are unlikely to encounter this much in a lot of Python code.

Example:

import asyncio
from collections.abc import AsyncIterable
class AsyncRange(AsyncIterable):
     def __init__(self, start, end):
         self.start = start
         self.end = end
     async def __aiter__(self):
         for i in range(self.start, self.end):
             await asyncio.sleep(0.1)
             yield i

async def example():
     it = aiter(AsyncRange(1, 4))
     print(await anext(it))
     print(await anext(it))

asyncio.run(example())

Back

any

any returns True if at least one element in something list-like (such as a list or tuple) is true. If all elements are false or if the list is empty, it returns False.

Example:

print(any([False, False, False]))

print(any([False, False, True]))

print(any([]))

Back

ascii

ascii returns a string containing a printable representation of an object. It escapes non-ASCII characters in the string using Unicode escape sequences, so the result can be safely printed or used where only ASCII characters are allowed.

Example:

print(ascii('Hello, world!'9)
print(ascii('Héllo'))

Back

bin

bin converts an integer number to a binary string prefixed with 0b. The result is a string that represents the binary equivalent of the number.

Example:

print(bin(10))
print(bin(255))

Back

bool

bool converts a value to a Boolean (True or False). If the value is considered true (e.g., non-zero numbers, non-empty lists), it returns True. Otherwise, it returns False.

Example:

print(bool(0))
print(bool(1))
print(bool([]))
print(bool([1, 2, 3]))
print(bool([1,2,'A']))

Back

breakpoint

breakpoint is used to pause the execution of a program and start an interactive debugger at that point. It is helpful for inspecting the state of a program during debugging.

Example:

def example():
     x = 10
     breakpoint()
     print(x)

example()

Back

bytearray

bytearray creates a modifiable sequence of bytes. It can be set with a string, a sequence of integers, or an iterable of bytes, and allows modification of the byte values.

Example:

ba = bytearray('hello', 'utf-8')
print(ba)
ba[0] = 72
print(ba)

Back

bytes

bytes creates an unmodifiable sequence of bytes. It can be initialized with a string, a sequence of integers, or an iterable of bytes. Unlike bytearray, the result cannot be modified after creation.

Example:

b = bytes('hello', 'utf-8')
print(b)

b[0] = 72  #  -> ERROR

b = bytes([65, 66, 67])
print(b)

Back

callable

callable checks if an object appears to be callable, meaning it can be called like a function. It returns True if the object can be called, and False otherwise.

Example:

print(callable(print))
print(callable(42))

Back

chr

chr converts an integer (representing a Unicode code point) to its corresponding character. It returns the character as a string. It is the inverse of ord.

Example:

print(chr(65))
print(chr(128513))  #  '😁'

Back

classmethod

classmethod is used to define a method in a class that is connected to the class. This means that the method receives the class as its first argument instead of an instance.

Example:

class Example:
    @classmethod
    def greet(cls):
        return f"Hello from {cls.__name__}"

print(Example.greet())

Back

compile

compile builds source code into a code object that can be executed by the exec() or eval() functions. It takes a string of code and returns a code object which can be run later.

Example:

code = compile('print("Hello, world!")', '', 'eval')
exec(code)

Back

complex

complex creates a complex number from a real and an optional imaginary part. The result is a number with both real and imaginary components.

In math, you would typically use i to represent the imaginary portion. Because i is a common variable name, Python uses j instead.

Example:

z = complex(2, 3)
print(z)
z = z * z
print(z)
y = complex('1+2j')
print(y)
print(z*y)

Back

delattr

delattr removes an attribute from an object. You need to provide the object and the name of the attribute as a string. If the attribute does not exist, it raises an AttributeError.

Example:

class Example:
    def __init__(self):
        self.an_attribute = 10
example = Example()
delattr(example, 'an_attribute')
example.an_attribute
#Traceback (most recent call last):
#  File "", line 1, in 
#AttributeError: 'Example' object has no attribute 'an_attribute'

Back

dict

dict creates a dictionary, which is a collection of key-value pairs. You can initialize it with key-value pairs, or with other mappings or sequences.

More commonly, dictionaries will be constructed from the literal syntax using { and }.

Example:

d = dict(a=1, b=2)
print(d)
d = dict([('a', 1), ('b', 2)])
print(d)
d = {'a': 1, 'b': 2}
print(d)

Back

dir

dir returns a list of valid attributes for an object. If no object is passed, it returns a list of names in the current local scope.

Example:

class MyClass:
    def method(self):
        pass

print(dir(MyClass))
print()
print(dir())

Back

divmod

divmod takes two numbers and returns a tuple containing their quotient and remainder.

This is like division before you learned fractions in math class. In my math memory, I would write something like “9 / 4 = 2r1”. The “2” and the remainder of “1” are what divmod returns.

Example:

print(divmod(9, 4))
print(divmod(15, 6))

Back

enumerate

enumerate gives a counting number along with values when looping on something list-like. You can change where the counting number starts by using the start keyword argument.

Example:

for index, value in enumerate(['apple', 'banana']):
    print(index, value)

for index, value in enumerate(['cherry', 'date'], start=1):
    print(index, value)

Back

eval

eval evaluates a string containing Python code and returns the result. Be careful when using eval with untrusted data, as it can execute arbitrary code.

Example:

print(eval('2 + 3'))
x = 10
print(eval('x * 2'))

Back

exec

exec executes a string containing Python code. Unlike eval, which only evaluates expressions (i.e., simple code that returns a value), exec can execute complex code including statements, functions, and class definitions. Be careful when using exec with untrusted data, as it can execute arbitrary code.

Example:

code = '''
def greet(name):
    return f"Hello, {name}!"
'''

exec(code)
print(greet('Alice'))

Back

filter

filter takes something list-like and checks every value with a function that returns either True or False. Only the values that return True are included in the result.

When the function is None, the resulting list only includes items that are truthy.

Example:

def is_even(n):
    return n % 2 == 0

print(list(filter(is_even, [1, 2, 3, 4])))
print(list(filter(None, [0, 1, 2, '', 'hello'])))

Back

float

float converts a number or a string to a floating-point number. It can handle integer values, floating-point literals, and strings representing numbers.

Example:

print(float(10))
print(float('3.14'))
print(float('1e-4'))

Back

format

format outputs a value according to a specified format string. It allows you to control how numbers and strings are presented, such as setting decimal places or padding.

There are lots of options you can learn about to do string formatting. All the messy details are in the Format Specification.

Example:

print(format(123.4567, '.2f'))
print(format(42, '04d'))
print(format('hello', '^10'))

Back

frozenset

frozenset creates an unmodifiable version of a set. It can be set with anything list-like, and supports set operations like unions and intersections, but without the ability to add or remove elements.

Example:

fs = frozenset([1, 2, 3, 4])
print(fs)
fs2 = frozenset([3, 4, 5, 6])
print(fs | fs2)  # Union
print(fs & fs2)  # Intersection

Back

getattr

getattr retrieves the value of an attribute from an object. If the attribute does not exist, it can return a default value if provided; otherwise, it raises an AttributeError.

Example:

class Example:
    def __init__(self):
        self.an_attribute = 10

example = Example()
print(getattr(example, 'an_attribute'))
print(getattr(example, 'another_attribute', 42))

Back

globals

globals returns a dictionary representing the current global symbol table. This dictionary contains all the global variables and their values in the current scope.

Example:

x = 10
print(globals())
print(globals()['x'])

Back

hasattr

hasattr checks if an object has a specified attribute. It returns True if the attribute exists and False otherwise.

Example:

class Example:
    def __init__(self):
        self.an_attribute = 10

example = Example()
print(hasattr(example, 'an_attribute'))
print(hasattr(example, 'another_attribute'))

Back

hash

hash returns the hash value of an object, which is an integer used for hash-based operations like dictionary key lookups. The object must be immutable (i.e., unchanging), such as strings, numbers, or tuples containing only immutable elements.

Example:

print(hash('hello'))
print(hash((1, 2, 3)))
print(hash('m'))
print(hash('n'))

Back

help

help provides a helpful summary of information about an object, such as a module, function, class, or method. It displays documentation and usage information.

Example:

print(help(abs))

Back

hex

hex converts an integer to a hexadecimal string, prefixed with 0x. The result represents the number in base-16 notation.

Example:

print(hex(255))
print(hex(1234))
print(hex(65535))

Back

id

id returns a unique identifier for an object. This identifier is a constant integer that is guaranteed to be unique and constant for the object during its lifetime.

Example:

x = 'hello'
print(id(x))
y = [1, 2, 3]
print(id(y))

Back

input

input reads a line of text from the user and returns it as a string. You can provide a prompt string that is displayed to the user before they enter their input.

Example:

name = input('Enter your name: ')
print(name)
### Does not work in the Browser! Copy it into Thonny

Back

int

int converts a number or a string to an integer. It can handle decimal numbers and strings representing integers, as well as numbers in other bases if specified.

Example:

print(int('42'))
print(int(3.14))
print(int('101', base=2))  # Convert _binary_ string to integer
print(int('ff', base=16))  # Convert _hexadecimal_ string to integer

Back

isinstance

isinstance checks if an object is an instance or subclass of a specified class or tuple of classes. It returns True if the object matches the class, and False otherwise.

Example:

print(isinstance(10, int))
print(isinstance('hello', int))
print(isinstance('hello', str))
print(isinstance(10, (float, int)))
print(isinstance([], list))

Back

issubclass

issubclass checks if a class is a subclass of another class or a tuple of classes. It returns True if the class is a subclass, and False otherwise.

Example:

class A:
    pass

class B(A):
    pass

print(issubclass(B, A))
print(issubclass(A, B))
print(issubclass(B, (A, object)))

Back

iter

iter returns an iterator object for something list-like. Iterators allow you to traverse through items one at a time.

Example:

it = iter([2, 1])
print(next(it))
print(next(it))
print(next(it))   # ERROR, no next item

Back

len

len (for “length”) returns the number of items in something list-like, such as a list, tuple, or string. It provides the count of elements or characters contained in the object.

Example:

print(len([1, 2, 3]))
print(len((1, 2, 3, 4)))
print(len('hello'))

Back

list

list creates a new list object from an iterable or sequence. If no argument is provided, it returns an empty list. It is commonly used to convert other data types into lists.

More commonly, lists are constructed from the literal syntax using [ and ].

Example:

print(list('abc'))
print(list((1, 2, 3)))
print(list(range(3)))
print([1, 2])

Back

locals

locals returns a dictionary representing the current local symbol table. This dictionary includes all local variables and their values in the current scope.

Example:

def example():
    x = 10
    y = 20
    return locals()

print(example())

Back

map

map applies a specified function to each item in something list-like and returns the results. It is useful for processing or transforming elements in a collection.

Example:

def square(x):
    return x * x

print(list(map(square, [1, 2, 3, 4])))
print(list(map(str, [1, 2, 3])))

Back

max

max returns the largest item from something list-like or among two or more arguments. It can also take a key function to determine the maximum value based on custom criteria.

Example:

print(max([1, 2, 3, 4]))
print(max(10, 20, 30))
print(max(['apple', 'banana', 'pear'], key=len))

Back

memoryview

memoryview creates a memory view object from a bytes-like object. This view allows you to access the data without copying it. It is useful for handling large data buffers more efficiently.

Example:

mv = memoryview(b'hello')
print(mv[0])
print(mv[1:4].tobytes())

Back

min

min returns the smallest item from something list-like or among two or more arguments. It can also take a key function to determine the minimum value based on custom criteria.

Example:

print(min([1, 2, 3, 4]))
print(min(10, 20, 30))
print(min(['apple', 'banana', 'pear'], key=len))

Back

next

next retrieves the next item from an iterator. You can also provide a default value to return if the iterator is exhausted; otherwise, it raises a StopIteration exception.

Example:

it = iter([1, 2])
print(next(it))
print(next(it))
print(next(it, 'No more items'))
print(next(it)) # ERROR!! no next item

Back

object

object returns a new featureless object. This is the base for all objects in Python.

Example:

obj = object()
print(obj)
print(isinstance(obj, object))

Back

oct

oct converts an integer to its octal string representation, prefixed with 0o. This string represents the number in base-8 notation.

Example:

print(oct(8))
print(oct(64))

Back

open

open opens a file and returns a file object. You can specify the mode in which the file is opened (e.g., read, write).

Example:

with open('example.txt', 'w') as f:
    f.write('Hello World')

with open('example.txt') as f:
    content = f.read()

print(content)
print()
import os # operating system
print("Dateien auf dem Server: ")
for file in sorted(os.listdir(".")):
  print("{:>7}: {:<14}".format(os.path.getsize(f),f))

Back

ord

ord function returns the Unicode code point of a single character string. This integer represents the character in Unicode. It is the inverse of chr.

Example:

print(ord('A'))
a = ord('😁')
print(a, bin(a), hex(a))

Back

pow

pow calculates the power of a number. This function behaves like the ** operator (e.g., 2**3).

Example:

print(pow(2, 3))

Back

print

print outputs text or other data to the console. You can provide multiple arguments, and it will convert them to strings and display them, separated by spaces. You can also specify end characters and separators.

Example:

print('Hello, world!')
print('The answer is', 42)
print('Hello', end='!\n')

Back

property

property creates a property attribute in a class. This allows you to define methods that can be accessed like attributes. You can use it to control access to attributes and define custom getter, setter, and deleter methods.

Example:

class Example:
    def __init__(self, value):
            self._value = value
    @property
    def value(self):
            return self._value
    @value.setter
    def value(self, new_value):
            self._value = new_value

example = Example(10)
print(example.value)
example.value = 20
print(example.value)

Back

range

range generates counting numbers, starting from a specified start value up to, but not including, an end value. It can also accept a step value to define the increment between numbers.

Example:

print(list(range(5)))
print(list(range(2, 8)))
print(list(range(1, 10, 2)))

Back

repr

repr returns a string that represents an object in a way that could be used to recreate the object, if possible. It is intended for debugging and development, and often includes more details than the string representation provided by str.

Example:

print(repr('hello'))
print(repr([1, 2, 3]))
print(repr({'key': 'value'}))

Back

reversed

reversed returns something list-like in the reverse order. It does not modify the original.

Example:

print(list(reversed([1, 2, 3, 4])))
print(list(reversed('hello')))

Back

round

round takes a number and rounds to a specified number of decimal places. If no number of decimal places is specified, it rounds to the nearest whole number.

Example:

print(round(3.14159, 2))
print(round(2.71828))
print(round(1.5))

Back

set

set creates a new set from something list-like. Sets are collections of unique elements and support operations like unions, intersections, and differences.

Sets are commonly constructed from the literal syntax using { and }.

Example:

a = set([1, 2, 3, 2, 1])
print(a)
print(set('hello'))
print(set())
print(type({1, 2, 3, 4}))

Back

setattr

setattr sets the value of an attribute on an object. If the attribute does not already exist, it is created. You provide the object, the name of the attribute, and the value to set.

Example:

class Example:
    def __init__(self):
        self.an_attribute = 10

example = Example()
print(example.an_attribute)

setattr(example, 'an_attribute', 20)
print(example.an_attribute)

setattr(example, 'another_attribute', 30)
print(example.another_attribute)

Back

slice

slice creates a slice object that specifies how to extract part of something list-like. It takes up to three arguments: start, stop, and step.

More commonly, slices use the literal syntax of : for conciseness (e.g., items[1:4]).

Example:

s = slice(1, 4)
items = [10, 20, 30, 40, 50]
print(items[s])
s = slice(0, 4, 2)
print(items[s])
print(items[1:4])

Back

sorted

sorted returns a new list containing all items from something list-like, sorted in ascending order. You can also provide a custom sorting function and specify whether to sort in ascending or descending order.

Example:

a = [3, 1, 4, 1, 5, 9]
print(sorted(a), a)
print(sorted(['apple', 'banana', 'pear'], key=len))
print(sorted([3, 1, 4, 1, 5, 9], reverse=True))

Back

staticmethod

staticmethod defines a method within a class that does not depend on class or instance-specific data.

Example:

class Example:
    @staticmethod
    def greet(name):
        return(f'Hello, {name}!')

print(Example.greet('Mark'))

Back

str

str converts an object to its string representation. This is useful for displaying or working with textual data. You can use it to convert numbers, lists, or other objects into strings.

Example:

print(str(123))
print(str(3.14))
print(str([1, 2, 3]))

Back

sum

sum adds up all the items in something list-like containing numbers.

Example:

print(sum([1, 2, 3, 4]))
print(sum((10, 20, 30)))
print(sum(range(5)))
Back

super

super returns a proxy object that represents the parent classes of the current class. It is used to call methods from a parent class, allowing you to extend or modify inherited methods.

Example:

class A:
    def greet(self):
        return 'Hello from A'

class B(A):
    def greet(self):
        return super().greet() + ' and B'

b = B()
print(b.greet())

Back

tuple

tuple creates a new tuple object from something list-like. Tuples are immutable, meaning their contents cannot be changed after creation. If no argument is provided, it returns an empty tuple.

Example:

print(tuple([1, 2, 3]))
print(tuple('abc'))
print(tuple())

Back

type

type function returns the type of an object, which is a class that the object belongs to.

Example:

print(type(123))
print(type('hello'))
print(type([1, 2, 3]))
class Example:
    pass

print(type(Example()))

Back

vars

vars returns the __dict__ attribute of an object, which is a dictionary containing its writable attributes. If no object is provided, it returns the __dict__ of the current local symbol table.

Example:

class Example:
    def __init__(self):
        self.an_attribute = 'value1'
        self.another_attribute = 'value2'

example = Example()
print(vars(example))
print()
print(vars())

Back

zip

zip takes two or more list-like things and aggregates their items into tuples. Each tuple contains elements from the corresponding positions of the inputs. If the inputs are of different lengths, zip stops at the shortest one.

Example:

print(list(zip([1, 2, 3], ['a', 'b', 'c'])))
print()
print(list(zip('abc', [1, 2, 3], [True, False, True])))
print()
print(list(zip([1, 2], ['x', 'y', 'z'])))

Back

__import__

__import__ is a low-level function used by the import statement to load modules. It takes a module name as a string and returns the imported module.

You should probably use import instead.

Example:

math = __import__('math')
print(math.sqrt(16))
print()
os = __import__('os')
print(os.name)

Back

   Hits:    
$Id: index.html 623 2024-06-14 06:56:43Z voss $