What makes functions different from simple
data types like numbers and characters?
While there are many differences, Python aims to treat functions much like other values.
One way to see this is the way that functions can be used, like numbers, as arguments in expressions.
This is a somewhat advanced topic, initially
seeming not so useful. The example here is a
simple problem, finding the word which has the
most "e" letters in a list. To do this, two
features of Python not yet introduced are used:
max function of a list and
count method. Examples of these
1 2 3 4
>>> max([8,2,5,19,3]) 19 >>> "multiform plastic".count('i') 2
max is seen to be a function
that finds the largest value in a sequence. The
count method tells us how many of
a given value occur in a string.
Back to solving the problem, shown in an example
that takes advantage of a little-known feature of
max function, which is a keyword
|R = word.count("e")|
|T = max(L,key=ecount)|
|A = ["let","the","world","see","which"]|
The "maximum" word in the list is world,
since it is the word that appears last in
the dictionary. However, what if we would
like to judge "maximum" not on the basis of
alphabetic order, but by the number of "e"
letters in the word? It turns out that this
is an option to
max, where the
caller can specify a function called on
each word, before comparison is made.