Built-in Functions

Built-in Functions#

Python provides a number of built-in functions. Some of these have already been mentioned, such as print.

Mathematical Functions#

Python provides:

  • abs returns the absolute of a number.

  • pow raises a number to a specified power.

  • round rounds a number to specified number of decimal places.

print(abs(-10))
print(pow(2, 2))
print(round(2.3141572, 2))

Iterables#

Iterables are objects that can be looped over, we saw some examples of them in Data Structures, these include lists, sets, tuples etc.. but also strings. The data type contained within the iterable can determine the built-ins that can be used.

On numerical data types (int, float):

  • max

  • min

  • sum

On strings (str):

  • join

On all:

  • len

numerical_list = [0, 1, 2, 3, 4]

print(max(numerical_list))
print(min(numerical_list)) 
print(sum(numerical_list)) 
print(len(numerical_list))

print(sum(numerical_list)/len(numerical_list)) # Calculates the mean

string_tuple = ("H", "e", "l", "l", "o")

print("".join(string_tuple)) # joins the iterable together into a single string separated by whatever is contained within the first "".

Python also provides other useful built-in functions, for instance:

  • range

  • enumerate

initial_range = range(0, 10, 2) # starts counting from 0, finishes before 10, with a step size of 2

print([x for x in initial_range]) # using list comprehension to unpack the values

initial_enumerate = enumerate(range(10, 20, 2)) # enumerate provides a counter for the number of iterables

print([x for x in initial_enumerate]) # the first number in each tuple is the counter, the second is the value from the range.

Another example of enumerate is shown below for showing the third element of the list (in reality though, we would just examine the value at that index my_string_list[2]).

my_string_list = ["item1", "item2", "item3"]
for counter, value in enumerate(my_string_list):
    if counter==2:
        print(value)

Task#

You have been given a list of numbers below. Can you find the sum of the even numbers and the sum of the odd numbers?

numbers = [3, 7, 8, 19, 102, 45, 78, 43]

#Your code here