Python Built in Functions

The many Built-in functions are hands down one of the most important parts of the Python programming language. Not only are they so commonly used, but there are many things that are only possible with the use of these functions. There are dozens of built-in functions, each with their unique abilities.

In this Section, we have a compilation of all the Built-in functions in Python. Each Built-in function is given a brief description and a single example. There is also a link for each Built-in Function which leads to a more detailed page on that function with more examples. Make sure to check them out, you’ll be missing out otherwise.


Compilation

1. abs()

The Python abs() Built-in-Function returns the absolute value for a given number. In the case of a complex number, the absolute value is the magnitude of it’s real and imaginary parts.

>>> abs(-5.6)
5.6

2. chr()

The Python chr() function is a built-in function that returns the string representing a character whose Unicode is an integer. This function is the reverse of the ord() function, which takes a number and outputs it’s ASCII equivalent.

>>> chr(97)
'a'

3. callable()

A callable object is an object that can be called. The Python callable() built-in function determines whether an object is callable or not. If it is, it returns True. Otherwise, it returns False.

>>> callable(5)
False

4. complex()

A complex number is a number that can be expressed in the form a + bi. The complex function takes integers or strings as inputs and returns an appropriate complex number. Attempting to pass a inappropriate value will possibly result in a ValueError.

>>> complex(3)
(3+0j)

>>> complex(-3,-2)
(-3-2j)

5. dict()

The python dict function is used to create dictionaries. You can, of course create them manually, but this function allows for greater flexibility and options while creating dictionaries. You may for instance, pass a dictionary into this function, combining it with others to create a larger dictionary.

>>> dict({"a":1, "b":2}, c = 3)
{'a': 1, 'b': 2, 'c': 3}

>>> list = [["a",1],["b",2]]
>>> dict(list)
{'a': 1, 'b': 2}

6. dir()

The Python dir() function has the ability to retrieve a list of all attributes and methods belonging to any object. If no object is specified, the dir() function will return all the module names in the local namespace.

X = ["Apple", "Orange", "Grape"]

print(dir(X))

7. enumerate()

The enumerate() takes as input a sequence, iterates over it including a counter for every element, returning it as an enumerate object. The benefit of having an enumerate object is that you can place it in a loop to iterated over.

X = "String"
print(list(enumerate(X)))
[(0, 'S'), (1, 't'), (2, 'r'), (3, 'i'), (4, 'n'), (5, 'g')]

8. eval()

eval is a built-in-function used in python, eval function parses the expression passed to it and evaluates it as a python expression. Once this expression has been evaluated the value is returned. The eval function is typically used to evaluate mathematical functions.

x = 5
y = 10
z = eval('x + y')
print(z)   # Outputs 15

9. filter()

The Python Filter function, as the name implies is used to filter through iterables or sequences such as lists, tuples and dictionaries. Before calling the filter function however, you need to have an appropriate function created that will be used to test each element in the iterable to see if it qualifies or not. If it passes, it will be returned in the output, else not.

list1 = [3,5,4,8,6,33,22,18,76,1] 
result = list(filter(lambda x: (x%2 != 0) , list1)) 
print(result) 

9. float()

float() is a built-in Python function that converts a number or string to a float value and returns the result. If, due to invalid input this conversion fails, the Exception for ValueError or TypeError is thrown by the Python interprete.

>>> float('356')
356.0

>>> float(56)
56.0

10. hash()

Most objects in python have a “hash” number. The hash() function returns this hash value when it is applied to one of these objects. Objects with the __hash__() are the ones that have a hash value.

>>> hash('Hello World')
-2864993036154377761

>>> hash(True)
1

11. help()

The Python help() function provides an easy and internet free way to access the python documentation for a specific function, keyword, class or module.

>>> help(print)

12. input()

Python gives us the Built in Function input() as a quick and easy way to take input from the user. Calling this function gives the user the opportunity to enter on screen his input. The user’s input is then converted to a string and returned to the python program.

value = input("Please enter a value: ")

13. int()

The Python int function is used to return an integer from a the object passed into it’s parameters. It can also be used to convert numbers of different bases, (hexadecimal or binary) into integer.

>>> int(5.6)
5

>>> int('0101', 2)
5

14. iter()

The Python iter() function takes as input an object and returns an iterable object. This iterable object is useless on its own, but when used with something like a for loop or while loop, it becomes a powerful weapon. The iterable object it creates can be iterated over one element at a time.

lis = ['a','b','c','d','e']

X = iter(lis)
print(next(X), 'End')
print(next(X), 'End')
print(next(X), 'End')
print(next(X), 'End')
print(next(X), 'End')
print(next(X), 'End')

15. max()

The Python max function is used to find the ‘max’ value of a specific sequence, iteratable and more. By changing it’s parameters we can even change how this max value is calculated.

>>> max('a','A')
'a'

>>> x = [5,7,8,2,5]
>>> max(x)
8

>>> x = ["Apple", "Orange", "Automobile"]
>>> max(x, key = len)
'Automobile'

16. min()

The Python min function is used to find the ‘min’ value of a specific sequence or iteratable. By changing it’s parameters we can even change how this min value is calculated.

>>> min('a','A')
'A'

>>> x = [5,7,8,2,5]
>>> min(x)
2

>>> x = ["Grape", "Mango", "Fruit", "Strawberry"]
>>> min(x)
'Fruit'

17. len()

As the name suggests, the Python len Function is used to calculate the length of an sequence or iteratable. The len function will count the number of elements within the sequence or iteratable.

>>> X = (2, 3, 1, 6, 7)
>>> len(X)
5
>>> len("String")
6

18. list()

This article covers the use of the Python list function. The Python list function takes as input an iterable and returns a object of type list. This function allows for greater flexibility and speed while creating lists objects as opposed to creating them normally.

>>> list("Hello")
['H', 'e', 'l', 'l', 'o']

>>> list({1:"a", 2:"b", 3:"c"})
[1, 2, 3]

19. map()

The map() function is used apply a specified function to a given iterable and return the result in the form of an iterable object (lists, tuples, sets). There may be more than iterable passed into the map() function, hence the dots. However, the more iterables, the more parameters the given function must have.

def inc(x):
    x = x + 1
    return x

lis = [1,2,3,4,5]
result = map(inc,lis)

for x in result:
    print(x)
2
3
4
5
6

20. next()

The Python next function is used with iterables. It has the ability to retrieve the ‘next’ item in the iterable’s sequence. If it has reached the end of the iterable, it has the ability to output a default value.

X = iter(["Apple", "Banana", "Cucumber"])
print(next(X))
print(next(X))
print(next(X))
print(next(X))

21. ord()

The ord() function takes a single character, or string of length one as input and returns it’s corresponding Unicode value. For instance ord('a') will return 97, where 97 is the Unicode value representing a.

>>> ord('a')
97

>>> ord('A')
65

22. reversed()

The Python reversed function provides us with a quick and easy way to reverse the order of all the elements in a sequence. It takes as input an appropriate sequence, such as a list, and returns an iteratable object.

X = [3,4,5]
B = reversed(X)
print(list(B))
[5, 4, 3]

23. range()

The Python range function is used to create a sequence of numbers from a given start point to a given end point, with a specified increment. The sequence of numbers generated by the range() function are often used in loops, especially the for loop.

>>> list(range(10,20,2))
[10, 12, 14, 16, 18]

24. reduce()

The Python reduce function has the unique ability to perform a function passed as it’s argument on to first two elements of the list, then applies it again to the result and the next element, and so on, until the entire list has been processed.

from functools import reduce

# Define a list of numbers
numbers = [1, 2, 3, 4, 5]

# Use reduce() to compute the product of the numbers
product = reduce(lambda x, y: x * y, numbers)

print(product)  # Outputs 120

The reduce function is a part of the functools, so every time you want to use reduce, you have to import functools first.


25. sorted()

The python sorted function can be used to sort sequences of values in all kinds of ways. For instance, it can sort a list of strings in alphabetical order, or a list of numerical values in ascending or descending order.

>>> X = [4,5,7,3,1]
>>> sorted(X)
[1, 3, 4, 5, 7]

26. str()

The str function is used to create string representations of objects. It does not alter the object itself. It simply returns a new string object. The string function comes with it’s own encoding and error handling scheme to aid it’s conversion process.

>>> str(5)
'5'

>>> X = [5,6,7]
>>> str(X)
'[5, 6, 7]'

27. set()

The set() method in Python is used to create a collection of unique elements. It removes duplicates from a sequence and returns a new set object.

my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set)  # Outputs {1, 2, 3, 4, 5}

28. sum()

Calculating the sum of values is a common tasks required in many applications. Instead of individually adding each element, why not use an Built-in function instead? Python gives us the sum() function which has the ability to add all the elements in an iteratable and returns the sum.

>>> X = [1,2,5,3,6,7]
>>> sum(X)
24

29. tuple()

The Python tuple() function takes a single input argument, an iterable which may be a list, dictionary, sequence or iterator object and returns a tuple equivalent. In the event that an iterable is not included, an empty tuple will be returned.

>>> tuple("Hello")
('H', 'e', 'l', 'l', 'o')

>>> tuple([1,2,3,4,5])
(1, 2, 3, 4, 5)

30. type()

The Python type Function has two uses. The first, if a single object is passed into it’s parameters, it will return the type of that object. The second, it can be used to create a new type object if three inputs are given.

>>> type(5)
<class 'int'>

>>> type([5])
<class 'list'>

This marks the end of the Python Built in Functions Compilation Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions be can be directed to the comments section below.

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments