# 9.8. Lists and functions¶

There are a number of built-in functions that can be used on lists that allow you to quickly look through a list without writing your own loops:

The `sum()`

function only works when the list elements are
numbers. The other functions (`max()`

, `len()`

,
etc.) work with lists of strings and other types that can be comparable.

- True
- The max and len functions can work on any list.
- False
- The max and len functions can work on any list, but the sum function can only work on lists made of numbers.

Q-2: True or False? The max, sum, and len functions can work on any list.

We could rewrite an earlier program that computed the average of a list of numbers entered by the user using a list.

First, the program to compute an average without a list:

In this program, we have `count`

and `total`

variables to keep the number and running total of the user’s numbers as
we repeatedly prompt the user for a number.

We could simply remember each number as the user entered it and use built-in functions to compute the sum and count at the end.

We make an empty list before the loop starts, and then each time we have a number, we append it to the list. At the end of the program, we simply compute the sum of the numbers in the list and divide it by the count of the numbers in the list to come up with the average.

- sum
- The sum function is used to add up all the values in a list to get the numerator of the average.
- avg
- Unfortuantely, avg is not a function in Python.
- append
- append is a list method. It may be used to add elements to a list that are then averaged together, but not to compute the average itself.
- len
- The len function is used to count the elements in a list to get the denominator of the average.
- max
- The max function is not used in averaging. It returns the largest element in a list.

Q-5: Which of the following built-in functions can be used on lists to compute the average of the list? Select all that apply.

- 7
- Yes, there are 7 items in this list even though two of them happen to also be lists.
- 8
- len returns the number of top level items in the list. It does not count items in sublists.
- 9
- len returns the number of top level items in the list. It does not count items in sublists.
- 3
- len returns the number of top level items in the list, not the number of brackets.

Q-6: What is printed by the following statements?

```
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(len(alist))
```