Execute Program

Python for Programmers: Built-in Functions

Welcome to the Built-in Functions lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Python comes with "batteries included", which means that its standard library is larger than many other languages'. Much of that functionality is inside of modules that we can import. However, some of it is available in the global namespace as "built-ins".

  • We've already seen one built-in function, len. This lesson covers some other useful built-ins.

  • There are a few mathematical built-in functions. sum adds all values in an iterable together.

  • >
    sum([1, 2, 3, 4])
    Result:
    10Pass Icon
  • Calling sum on an empty iterable returns 0.

  • >
    sum([])
    Result:
    0Pass Icon
  • The sum function takes an optional start argument, which has a default value of 0. This is the initial value for the internal counter used when summing the values.

  • >
    sum([1, 2, 3], start=4)
    Result:
    10Pass Icon
  • If the list is empty, its sum (0) is added to the initial value.

  • >
    sum([], 6)
    Result:
    6Pass Icon
  • sum is primarily intended for numeric types. However, it also works with other data types that support the + operator. In those cases, we need to provide a proper start value.

  • >
    # This is equivalent to `[1, 2] + [3, 4] + [5, 6]`.
    sum([[1, 2], [3, 4], [5, 6]], start=[])
    Result:
    [1, 2, 3, 4, 5, 6]Pass Icon
  • If we remove the start argument in that code, we get an error. The problem is that start defaults to 0. Trying to add 0 to a list is an error.

  • >
    sum([[1, 2], [3, 4], [5, 6]])
    Result:
    TypeError: unsupported operand type(s) for +: 'int' and 'list'Pass Icon
  • It seems like sum should also work with strings, like sum(["a", "b"], start=""). However, that doesn't work. Python even has a specific error message saying why. Check the error message below. Python really does not want us to sum strings like this!

  • >
    sum(["a", "b"], "")
    Result:
    TypeError: sum() can't sum strings [use ''.join(seq) instead]Pass Icon
  • Calling min(data) returns the smallest element in the iterable, while max returns the biggest.

  • >
    # Passing lists to `min` and `max`.
    data = [3, 5, 9, 7, 2]
    (min(data), max(data))
    Result:
    (2, 9)Pass Icon
  • min and max are both flexible with their arguments. We can pass a single iterable, as shown above. Or we can pass individual values as separate arguments. In that case, we get the smallest (or largest) of the arguments.

  • >
    # Passing individual arguments to `min` and `max`.
    (min(5, 2, 7), max(3, 8, 10))
    Result:
    (2, 10)Pass Icon
  • Calling min or max without elements raises a ValueError exception.

  • >
    max([])
    Result:
    ValueError: max() iterable argument is emptyPass Icon
  • Unlike sum, the min and max functions work with strings. For example, "a" < "b" < "c" < ... < "z". If the first characters of each string differ, the word with the "greater" letter is bigger. If the first characters are the same, Python compares the second characters, then the third, etc. This is called comparing in "lexicographic order".

  • >
    min("sword", "shield", "potion")
    Result:
    'potion'Pass Icon
  • >
    min("abr", "abd", "aca")
    Result:
    'abd'Pass Icon
  • Lists have a .sort method, which sorts the list. It changes the original list, which is OK in some situations. But we often want a sorted copy of a list without changing the original.

  • The sorted built-in takes any iterable, sorts it, and returns the sorted values as a list. Unlike .sort, sorted doesn't change the original iterable.

  • >
    data = [3, 2, 1, 4]
    sorted_data = sorted(data)
    (data[0], sorted_data[0])
    Result:
    (3, 1)Pass Icon
  • Strings are iterable, so we can pass them to sorted. We get back a list of letters sorted from a to z. sorted always returns a list, regardless of the iterable we pass it.

  • >
    my_word = "cat"
    sorted_letters = sorted(my_word)
    sorted_letters
    Result:
    ['a', 'c', 't']Pass Icon
  • Like .sort, sorted takes an optional reverse keyword argument. This flips the usual sorting order. For example, numbers are normally sorted from smallest to largest.

  • >
    data = [2, 1, 3]
    sorted_data = sorted(data)
    sorted_data
    Result:
    [1, 2, 3]Pass Icon
  • >
    data = [2, 1, 3]
    sorted_data = sorted(data, reverse=True)
    sorted_data
    Result:
    [3, 2, 1]Pass Icon
  • sorted also takes an optional key argument. The key must be a function, which sorted calls on each iterable value. Then it sorts the values according to the function's return values. In the next example, we use it to sort cats by their ages.

  • >
    cats = [
    {
    "name": "Wilford",
    "age": 17
    }, {
    "name": "Keanu",
    "age": 2
    }, {
    "name": "Ms. Fluff",
    "age": 4
    }
    ]
    sorted_by_age = sorted(cats, key=lambda cat: cat["age"])
    sorted_by_age[0]["name"]
    Result:
    'Keanu'Pass Icon
  • >
    words = ["win", "surrender", "draw"]
    sorted_by_length = sorted(words, key=lambda word: len(word))
    sorted_by_length[0]
    Result:
    'win'Pass Icon