Python Built-in Functions

The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. In this article, I have explained a list of all functions of Python with examples.

In order to use these functions you donâ€™t have to install and import any module, These functions by default come with the python installation and are available to use directly.

List of Python Built-in Functions

The following are the most used built-in functions in Python. I have converted pretty much all functions and explained each one with examples below.

1. abs() Function

The `abs()` function in Python is used to find the absolute value of a number. The absolute value of a number is its distance from zero on the number line. For example, the absolute value of -50 is 50.

``````
# integer number
integer = -50
print('Absolute value of :', abs(integer))

# Output
# Absolute value of : 50

# floating number
floating = -50.28
print('Absolute value of :', abs(floating))

# Output
# Absolute value of : 50.28
``````

2. all() Function

The `all()` function in Python is used to determine whether all elements in an iterable (such as a list, tuple, or dictionary) are true. The function returns True if all elements in the iterable are true, and False otherwise.

``````
# all values true
List = [2, 4, 6, 8]
print(all(List))

# Output
# True

# one false value
List = [2, 4, 6, 8]
print(all(List))

# Output
# False

# one true value
List = [0, False, 8]
print(all(List))

# Output
# True

# empty iterable
List = []
print(all(List))

# Output
# True
``````

3. bin() Function

You can use the` bin()` function in Python to convert an integer number to its binary representation. The returned value is a string containing a binary number. The prefix `'0b'` is added to the string to indicate that the number is binary.

``````
# Python bin() function
number = 20
result = bin(number)
print (result)

# Output
# 0b10100
``````

4. bool()

You can use the `bool()` function in Python to convert a value to a Boolean (True or False) value. This function is used to check if a variable or expression is True or False.

``````
# Use Python bool()
test1 = []
print(test1,'is',bool(test1))

# Output
[] is False

# Python bool()
test1 = [0]
print(test1,'is',bool(test1))

# Output
[0] is True
``````

5. bytes()

The `bytes()` function in Python is used to create a bytes object. It returns a bytes object by encoding the string using the `'utf-8'` encoding.

``````
# Python bytes()
string = "Spark By Examples."
array = bytes(string, 'utf-8')
print(array)

# Output
# b'Spark By Examples.'
``````

6. callable() Function

You can use the` callable()` function in Python to determine if an object is callable, meaning it can be invoked as a function. The function returns True if the object is callable, and False otherwise.

``````
# Python callable() function
result = 15
print(callable(result))

# Output
# False
``````

7. exec() Function

You can use the `exec()` function in Python to execute a string of Python code. The string of code passed to the `exec()` function is treated as if it were a program and is executed.

``````
# Python exec() function
x = 12
exec('print(x==12)')
exec('print(x+6)')

# Output
# True
# 18
``````

8. sum() Function

You can use the `sum()` function in python is used to get the sum of numbers of an iterable, i.e., list.

``````
# Python sum() function
result = sum([2, 3, 4])
print(result)

# Output
# 9

# Use python sum
result = sum([2, 3, 4], 12)
print(result)

# Output
# 21
``````

9. any() Function

The `any()` function in Python returns True if at least one element in an iterable (e.g. list, tuple, etc.) is True. Otherwise, it returns False.

``````
# Python any() function
result = [6, 4, 2, 0]
print(any(result))

# Output
# True
``````

10. ascii() Function

The `ascii()` function in Python returns a string containing a printable representation of an object. Itâ€™s similar to the `repr()` function.

``````
# Python ascii() function
result = 'Spark By Examples'
print(ascii(result))

# Output
# 'Spark By Examples'
``````

11. bytearray()

You can use the python `bytearray()` function is used to returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size.

``````
# string with encoding 'utf-8'
string = "Spark By Examples."
arr = bytearray(string, 'utf-8')
print(arr)

# Output
# bytearray(b'Spark By Examples.')
``````

12. eval() Function

The `eval()` function in Python is used to evaluate a string as a Python expression. It takes a string as its argument and returns the result of the evaluated expression.

``````
# Python eval() function
result = 15
print(eval('result + 5'))

# Output
# 20
``````

13. float() Function

You can use the `float()` function in python is used to returns a floating-point number from a number or string.

``````
# Python float() function
print(float(5.38))

# Output
# 5.38
``````

14. format() Function

The python `format()` function is used to return a formatted representation of the given value.

``````
# float arguments
print(format(253.3567895, "f"))

# Output
# 253.356789
``````

15. frozenset()

You can use the python `frozenset()` function to return an immutable frozenset object initialized with elements from the given iterable.

``````
# tuple of letters
letters = ('s', 'p', 'a', 'r', 'k')
fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())

# Output
# Frozen set is: frozenset({'s', 'p', 'a', 'r', 'k'})
# Empty frozen set is: frozenset()
``````

16. getattr() Function

The python `gettr()` function is used to return the value of a named attribute of an object.

``````
# Python getattr() Function
class Details:
age = 35
name = "messi"

details = Details()
print('The age is:', getattr(details, "age"))
print('The age is:', details.age)

# Output
# The age is: 35
# The age is: 35
``````

17. globals() Function

The Python `globals()` function is used to return a dictionary of the current global symbol table.

``````
# Python globals() function
age = 35
globals()['age'] = 35
print('The age is:', age)

# Output
# The age is: 35
``````

18. hasattr() Function

You can use the `hasattr()` function in Python to check if an object has a given attribute. The function takes two arguments, the first is the object, and the second is the string name of the attribute. The function returns True if the object has the attribute and False if it does not.

``````
# Python hasattr() function
class MyClass:
x = 26

obj = MyClass()
result = hasattr(obj, 'x')
print(result)

# Output
# True

# Use hasattr() function
result = hasattr(obj, 'y')
print(result)

# Output
# False
``````

19. iter() Function

The `iter()` function in Python is used to create an iterator object from an iterable (e.g. a list, a tuple, a string, etc.).

``````
# Python iter() function
list = [2,4,6,8,7]
listIter = iter(list)
print(next(listIter))

# Output
# 2
``````

20. len() Function

You can use the `len()` function in Python to return the number of items in an object. The function can be used with various types of objects, such as strings, lists, tuples, dictionaries, etc.

``````
# Python len() function
String = 'Sparkbyexamples'
print(len(String))

# Output
# 15
``````

21. list() Function

You can use the `list()` function in Python to create a new list object. It can take an iterable object, such as a tuple or string, and convert it into a list.

``````
# python list() function using string
string = "spark"
result = list(string)
print(result)

# Output
# ['s', 'p', 'a', 'r', 'k']

# Use tuple list
my_tuple = (2, 5, 8)
my_list = list(my_tuple)
print(my_list)

# Output
# [2, 5, 8]
``````

22. locals() Function

The `locals()` function in Python is a built-in function that returns a dictionary of the current local symbol table. The keys in the dictionary are the names of local variables and the values are the values of the corresponding variables.

``````
# python local() function
result = 25
locals()['result'] = 25
print(result)

# Output
# 25
``````

23. map() Function

You can use PythonÂ `map()`Â function to apply the transformation function on each item of the iterable. We used to do this traditionally withÂ for loop, but by using map() function you can avoid using explicit for loop in your code. Using the map() function makes your code readable and user-friendly. Try to avoid the looping when possible and use the map() function instead.

Related: Python reduce() Function

Letâ€™s create a simple square() function and use it with map() function by taking a tuple of numbers. Here, is an example.

``````
# Create tuple of numbers
numbers = (2, 4, 6, 8, 5)
print("Original:", numbers)

# Create function square
def square(x):
return x * x

# Use map() function to apply a function
square_numbers = map(square, numbers)
result = list(square_numbers)
print("Result:",result)

# Output:
# Original: (2, 4, 6, 8, 5)
# Result: [4, 16, 36, 64, 25]
``````

24. memoryview() Function

The `memoryview()` function in Python is a built-in function that returns a memory view object of the given argument. A memory view is a safe way to expose the internal data of an object to Python code without creating a copy.

``````
#A random bytearray
result = bytearray('SPARK', 'utf-8')
mv = memoryview(result)

# access the memory view's zeroth index
print(mv[0])

# It create byte from memory view
print(bytes(mv[0:3]))

# It create list from memory view
print(list(mv[0:4]))

# Output
# 83
# b'SPA'
# [83, 80, 65, 82]
``````

25. object()

The `object()` function in Python is a built-in function that returns a new object. This object is an instance of the object class, which is the base class for all classes in Python.

``````
# Python object()
result = object()
print(type(result))
print(dir(result))

# Output
<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
``````

26. open() Function

You can use `open()` function in Python to open a file for reading or writing. It takes two arguments: the first is the name or path of the file, and the second is a string that specifies the mode in which the file should be opened.

``````
# opens python.text file of the current directory
result = open("python.txt")
# specifying full path
``````

27. chr() Function

The `chr()` function in Python is used to return the string representing a character whose Unicode code point is the integer.

``````
# It returns string
# representation of a char
result = chr(112)
print(result)

# Output
# P
``````

28. complex()

You can use the python `complex()` function to convert numbers or strings into complex numbers.

``````
# Python complex() function
# Passing single parameter
result = complex(3)
print(result)

# Output
(3+0j)

# Passing multiple parameters
result = complex(2,4)
print(result)

# Output
# (2+4j)
``````

29. delattr() Function

The `delattr()` function in Python is used to delete an attribute from an object. It takes two arguments, the first is the object and the second is the string name of the attribute to be deleted.

``````
# python delattr() function
class Student:
id = 122
name = "Sparkbyexamples"
email = "sparkbyexamples.com"
# Declaring function
def getinfo(self):
print(self.id, self.name, self.email)
result = Student()
result.getinfo()
delattr(Student,'course')
result.getinfo()

# Output
# AttributeError: course
``````

30. dir() Function

The` dir()` function in Python returns a list of names in the current local scope or the objectâ€™s namespace if an object is passed as an argument. This includes all attributes, methods, and variables that are defined in the objectâ€™s class and any superclasses. If the object passed as an argument has a `dir()` method defined, this method will be called and must return a list of attributes.

``````
# Python dir() function
result = dir()
print(result)

# Output
# ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
``````

31. divmod() Function

The` divmod()` function in Python returns a pair of numbers (a tuple) consisting of their quotient and remainder when using integer division. It takes two arguments, the first is the dividend and the second is the divisor.

``````
# Python divmod() function
result = divmod(8,4)
print(result)

# Output
# (2, 0)
``````

32. enumerate() Function

You can use the `enumerate()` function in Python to iterate over a sequence (such as a list, tuple, or string) and return an iterator that produces tuples containing the index and the value of each element of the sequence.

``````
# Python enumerate() function
result = enumerate([2,4,6])
print(result)
print(list(result))

# Output
# <enumerate object at 0x148ec2f9a2c0>
# [(0, 2), (1, 4), (2, 6)]
``````

33. dict() Function

The `dict()` function in Python is used to create a new dictionary. A dictionary is a data structure that stores key-value pairs, where each key is unique.

``````
# Python dict() function
result = dict()
result2 = dict(a=3,b=5)
print(result)
print(result2)

# Output
# {}
# {'a': 3, 'b': 5}
``````

34. filter() Function

The `filter()` built-in function in Python is used to filter out elements from an iterable (such as a list, tuple, or string) that do not meet a certain condition.

``````
# Python filter() function
def filterdata(x):
if x>5:
return x
result = filter(filterdata,(2,4,8))
print(list(result))

# Output
# [8]
``````

35. hash() Function

You can use the Python `hash()` function to get the hash value of an object. Python calculates the hash value by using the hash algorithm. The resulting hash value is an integer and is used to compare dictionary keys during a dictionary lookup.

``````
# Python hash() function
# integer value
result = hash(25)
print(result)

# Output
# 25

# decimal value
result2 = hash(27.4)
print(result2)

# Output
# 922337203685474331
``````

36. help() Function

The `help()` function in Python is used to get help information related to a specific object or module. When called without any arguments, it opens the Python help console, which allows you to search for and view information about various modules and objects. When called with an argument, it returns help information for that specific object or module.

``````
# Python help() function
info = help()
print(info)

# Output
# Welcome to Python 3.8's help utility!
``````

37. min() Function

You can use the `min()` function in Python to get the smallest item in an iterable or the smallest of two or more arguments. It takes one or more arguments, the first is a collection of elements and the second is key and returns the smallest element from the collection.

``````
# Python min() function
small = min(3335,325,2025)
small2 = min(2000.25,2025.35,5625.36,10052.50)
print(small)
print(small2)

# Output
# 325
# 2000.25
``````

38. set() Function

You can use the python `set()` function to create a new set object. A set is a collection of unique elements. The elements in a set can be of any type, including numbers, strings, and other objects. The order of elements in a set is not preserved.

``````
# Python set() function
result = set('spark')
print(result)

# Output
# 'k', 'p', 'r', 's', 'a'}
``````

39. hex() Function

You can use the `hex()` function in Python to convert an integer to a string representation of its hexadecimal value. The hexadecimal system uses base 16, and uses the digits 0-9 and the letters A-F to represent values.

``````
# Python hex() function
result = hex(5)
print(result)

# Output
# 0x5

# integer value
result = hex(425)
print(result)

# Output
# 0x1a9
``````

40. id() Function

The `id()` function in Python is used to get the identity of an object. The identity is an unique integer that is assigned to an object during its creation and remains constant throughout its lifetime.

``````
# Python id() function
# string object
result = id("Sparkbyexamples")
print(result)

# Output
# 23059105095920

# integer object
result = id(1200)
print(result)

# Output
# 23059106590064
``````

41. setattr() Function

The `setattr()` function in Python is used to set the value of an attribute of an object, creating the attribute if it does not already exist.

``````
# Python setattr() function
class Person:
pass

result = Person()
setattr(result, 'name', 'messi')
print(result.name)

# Output
# messi
``````

42. slice() Function

The `slice()` function in Python is used to create a slice object, which is used to extract a part of a sequence (e.g. a string, list, tuple, etc.).

``````
# Python slice() function
# Using slice() to extract a part of a list
numbers = [2, 4, 6, 8, 1, 5, 9]
print(numbers[slice(2, 7)])

# Output
# [6, 8, 1, 5, 9]

# Using slice() to extract a part of a string
string = "SparkbyExamples!"
print(string[slice(5, 9)])

# Output
# byEx
``````

43. sorted() Function

You can use the python built-in sorted() function to sort elements. By default, it sorts elements in ascending order but can be sorted in descending also. It takes four arguments and returns a new list after sorting.

``````
# Python sorted() function
str = "spark"
result = sorted(str)
print(result)

# Output
# ['a', 'k', 'p', 'r', 's']
``````

44. next() Function

You can use the Python `next()` function to fetch next item from the collection. It takes two arguments, i.e., an iterator and a default value, and returns an element.

``````
# Creating iterator
number = iter([326, 52, 17])
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)

# Output
# 326
# 52
# 17
``````

45. input() Function

The `input()` function in Python is used to read user input from the console.

``````
# Python input() function
val = input("Enter a value: ")
print("You entered:",val)
``````

46. int() Function

The` int()` function in Python is used to convert a value to an integer. The value can be a string, a float, or another type of number, and the function will convert it to an integer.

``````
# integer value
result = int(15)
print(result)

# float value
result = int(13.52)
print(result)

# string value
result = int('20')
print(result)

# Output
# 15
# 13
# 20
``````

47. isinstance() Function

You can use the `isinstance()` function in Python to determine if an object is an instance of a particular class or of a subclass thereof. The function takes two arguments: the object to be checked and the class or type to be checked against. If the object is an instance of the class or a subclass thereof, the function will return True, otherwise, it will return False.

``````
# Python isinstance() function
class MyParent:
pass

class MyChild(MyParent):
pass

result = MyChild()
print(isinstance(result, MyParent))

# Output
# True
``````

48. oct() Function

You can use the Python `oct()` function to get an octal value of an integer number. This function takes an argument and returns an integer converted into an octal string.

``````
# Python oct() function
result = oct(30)
print("Octal value of 30:",result)

# Output
# Octal value of 30: 0o36
``````

49. ord() Function

The `ord()` function in Python is used to return the integer representation of a character. The function takes a string of length one as an argument and returns its corresponding Unicode code point.

``````
# Python ord() function
print(ord('9'))

# Code point of an alphabet
print(ord('M'))

# Code point of a character
print(ord('&'))

# Output
# 57
# 77
# 38
``````

50. pow() Function

You can use the python `pow()` function to calculate the power of a number. It takes two arguments, the base number, and the exponent. It returns the result of raising the base number to the power of the exponent.

``````
# Python pow() Function
result = pow(2,5)
print(result)

# Output
# 32

# Use pow() Function
result = pow(3, 0.7)
print(result)

# Output
# 2.157669279974593
``````

51. print() Function

You can use the python `print()` function to output text or other data to the console. The text or data to be printed is passed as an argument to the function. For example

``````
# Python print() function
print("Sparkbyexamples")

# Output
# Sparkbyexamples
``````

52. range() Function

The `range()` function in Python is used to generate a sequence of numbers. This function takes three arguments: start, stop, and step. The start and step arguments are optional and default to 0 and 1 respectively.

``````
# Generate a range of numbers from 0 to 5
for x in range(6):
print(x)

# Output
# 0 1 2 3 4 5

# Convert range object to list
nums = list(range(3, 8))
print(nums)

# Output
# [3, 4, 5, 6, 7]
``````

53. reversed() Function

You can use the python `reversed()` function to return the reversed iterator of the given sequence.

``````
# Python reversed() function
# for string
String = 'Spark'
print(list(reversed(String)))

# for tuple
Tuple = ('S', 'p', 'a', 'r','k')
print(list(reversed(Tuple)))

# Output
# ['k', 'r', 'a', 'p', 'S']
``````

54. round() Function

The `round()` function in Python is used to round off the digits of a number to a specified number of decimal places and returns the floating point number.

``````
# Python round() function
# for integers
print(round(20))

# Output
# 20

# for floating point
print(round(20.6))

# Output
# 21

# even choice
print(round(4.6))

# Output
# 5
``````

55. issubclass() Function

The `issubclass()` function in Python is used to determine if a class is a subclass of a specified class.

``````
class Rectangle:
def __init__(rectangleType):
print('Rectangle is a ', rectangleType)

class Square(Rectangle):
def __init__(self):
Rectangle.__init__('square')

print(issubclass(Square, Rectangle))

# Output
# True
``````

56. Python str()

You can use the python `str()` to convert a specified value into a string.

``````
# Use Python str()
str('7')

# Output
# '7'
``````

57. tuple() Function

The `tuple()` function in Python is used to create a tuple. A tuple is an immutable (non-modifiable) collection of elements, enclosed in parentheses and separated by commas. Tuples can contain elements of different types, such as integers, strings, and other objects.

``````
# Creating a tuple with literals
result = tuple([3, 5, 7])
print(result)

# Output
# (3, 5, 7)

# Creating an empty tuple
result = tuple()
print(result)

# Output
# ()

# Creating a tuple from a string
result = tuple("Spark")
print(result)

# Output
# ('S', 'p', 'a', 'r', 'k')

# Creating a tuple from a list
list = [2,4,6,8]
result = tuple(list)
print(result)

# Output
# (2, 4, 6, 8)
``````

58. type()

The` type()` function in Python is used to determine the type of an object. It takes an object as its only argument and returns the type of the object.

``````
# python type()
List = [3, 5, 7]
print(type(List))

# Output
# <class 'list'>
``````

59. vars() Function

The `vars()` function in Python is used to return the dict attribute of an object if the object has a dict attribute. If the object does not have a dict attribute, `vars()` raises a TypeError.

``````
# Python vars() function
class Python:
def __init__(self, x = 15, y = 20):
self.x = x
self.y = y
result = Python()
print(vars(result))

# Output
# {'x': 15, 'y': 20}
``````

60. zip() Function

The Python `zip()` function is to used to combine multiple iterables into one iterable. It takes iterables (can be zero or more), makes it an iterator that aggregates the elements based on iterables passed, and returns an iterator of tuples.

``````
# Python zip() function
list1 = [2, 4, 6]
list2 = [3, 5, 7]
zipped = zip(list1, list2)
print(list(zipped))

# Output
# [(2, 3), (4, 5), (6, 7)]
``````

Conclusion

In this article, I have explained the list of the most used Python built-in functions and also explain each function with examples.

Happy Learning !!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.