Python provides a rich set of built-in functions that can be used directly without importing any libraries. Below are some commonly used built-in functions along with brief descriptions and examples.
1. Mathematical Funtcions
# Returns absolute value
>>> abs(-5)
5
# Returns the power; if third argument is given, returns remainder after division
>>> pow(2, 4)
16
>>> pow(2, 3, 10)
8
# divmod() returns quotient and remainder
>>> divmod(123, 10)
(12, 3)
>>> divmod(123, 5)
(24, 3)
# Rounds a number to nearest integer
>>> round(2.5)
2
>>> round(2.6)
3
# max() and min() return the maximum and minimum of a sequence
2. Type Conversion Functions
# str() converts other types to string
# list() and tuple() convert other iterables to list and tuple
# int() converts to integer
>>> int(1.5)
1
>>> int(1.9)
1
# float() converts to float
>>> float(1.3)
1.3
>>> float(1)
1.0
3. Sequence and Iteration Related Functions
# len() returns the length of an object
# reversed() returns a reverse iterator; can be applied to lists, tuples, strings, etc.
for i in reversed([1, 3, 2]):
print(i)
# output:
2
3
1
# Reverse in-place using .reverse() method
>>> my_list = [1, 3, 2]
>>> my_list.reverse()
>>> my_list
[2, 3, 1]
# slice() returns a slice object: slice(start, stop, step)
s = slice(2, 5)
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = my_list[s] # [3, 4, 5]
# zip() pairs elements from multiple iterators into a list of tuples
for item in zip([1, 2, 3], ['a', 'b', 'c']):
print(item)
(1, 'a')
(2, 'b')
(3, 'c')
# map() applies a function to every item of an iterable
def square(n):
return n ** 2
for num in map(square, [1, 2, 3, 4]):
print(num)
# 1
# 4
# 9
# 16
# filter() filters elements based on a function
def is_odd(x):
return x % 2 == 1
for num in filter(is_odd, [1, 2, 3, 4]):
print(num)
# 1
# 3
# sorted() returns a new sorted list from an iterable; can also take a key function
my_list = [1, 3, 2, 4]
sorted(my_list) # [1, 2, 3, 4]
# .sort() sorts the list in-place
my_list.sort()
my_list # [1, 2, 3, 4]
# reduce() from functools; applies a function cumulatively
from functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
result = reduce(add, numbers)
print(result) # 15
4. Logical and Comparison Functions
# any() returns True if any element of the iterable is truthy
>>> any([1, 3, 2, 0])
True
>>> any([])
False
>>> any([[]])
False
>>> any([[], 1])
True
# all() returns True if all elements of the iterable are truthy
>>> all([1, 3, 2, 0])
False
>>> all([])
True
>>> all([[], 1])
False
5. String Processing Functions
# ascii() returns a string containing a printable representation of an object
>>> ascii('1')
"'1'"
>>> ascii(1)
'1'
>>> ascii('a')
"'a'"
# repr() returns a string representation of an object
>>> repr(1)
'1'
>>> repr('1')
"'1'"
# ord() returns the Unicode code point of a character; chr() returns the character from a code point
>>> ord('1')
49
>>> ord('a')
97
>>> chr(1)
'\x01'
>>> chr('a') # Error: string cannot be interpreted as integer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
6. Base Conversion Functions
# bin() converts to binary string
>>> bin(10)
'0b1010'
# oct() converts to octal string
>>> oct(10)
'0o12'
# hex() converts to hexadecimal string
>>> hex(10)
'0xa'
7. Other Utility Functoins
# print() outputs text
# format() formats strings and numbers
>>> print(format("test", "^20")) # center alignment
test
>>> print(format("test", "<20")) # left alignment
test
>>> print(format("test", ">20")) # right alignment
test
# Format specifiers for numbers:
print(format(3, "b")) # binary: 11
print(format(97, "c")) # Unicode character: a
print(format(11, "d")) # decimal: 11
print(format(11, "o")) # octal: 13
print(format(11, "x")) # hexadecimal lowercase: b
print(format(11, "X")) # hexadecimal uppercase: B
print(format(11, "n")) # same as d: 11
print(format(11)) # same as d: 11
print(format(123456789, "e")) # scientific notation, 6 decimal places: 1.234568e+08
print(format(123456789, "0.2e")) # scientific notation, 2 decimal places: 1.23e+08
print(format(123456789, "0.2E")) # scientific notation, 2 decimal places (uppercase): 1.23E+08
print(format(1.23456789, "f")) # fixed-point, 6 decimal places: 1.234568
print(format(1.23456789, "0.2f")) # fixed-point, 2 decimal places: 1.23
print(format(1.23456789, "0.10f")) # fixed-point, 10 decimal places: 1.2345678900
print(format(1.23456789e+3, "F")) # fixed-point, large numbers output INF: 1234.567890
# input() gets user input
# range() generates a sequence of integers