Python Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.
Mathematical Functions
abs()
Returns the absolute value of a number.
print(abs(-7.25)) # Output: 7.25
round()
Rounds a number to a specified number of digits.
print(round(5.76543, 2)) # Output: 5.77
min() and max()
Returns the smallest or largest item in an iterable or of two or more arguments.
print(min(5, 10, 25)) # Output: 5
print(max(5, 10, 25)) # Output: 25
sum()
Sums the items of an iterator.
print(sum([1, 2, 3, 4, 5])) # Output: 15
Type Conversion
int(), float(), str()
Convert values to integer, float, or string.
print(int("12")) # 12
print(float("12")) # 12.0
print(str(12)) # "12"
list(), tuple(), set(), dict()
Constructors for creating collections.
print(list((1, 2))) # [1, 2]
Iterables and Iterators
len()
Returns the length (the number of items) of an object.
print(len("Hello")) # Output: 5
range()
Returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
enumerate()
Takes a collection (e.g. a tuple) and returns it as an enumerate object.
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
print(list(y)) # Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
zip()
Returns an iterator, from two or more iterables, where the first item in each iterator is paired together, and then the second item in each iterator are paired together etc.
a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")
x = zip(a, b)
print(list(x)) # Output: [('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica')]
sorted()
Returns a sorted list of the specified iterable object.
a = (1, 11, 2)
x = sorted(a)
print(x) # Output: [1, 2, 11]
Input/Output
print()
Prints to the standard output device.
print("Hello", "World", sep="-") # Output: Hello-World
input()
Allow user input.
# x = input('Enter your name:')
open()
Opens a file and returns a file object.
# f = open("demofile.txt", "r")
Object Introspection
type()
Returns the type of an object.
print(type(5)) # Output: <class 'int'>
id()
Returns the identity of an object.
x = ('apple', 'banana', 'cherry')
print(id(x))
dir()
Returns a list of the specified object's properties and methods.
class Person:
name = "John"
age = 36
country = "Norway"
print(dir(Person))
help()
Executes the built-in help system.
# help(print)
Dynamic Execution
eval()
Evaluates and executes an expression.
x = 'print(55)'
eval(x) # Output: 55
exec()
Executes the specified code (or object).
x = 'name = "John"\nprint(name)'
exec(x) # Output: John