Lists as arguments and return values
Your own functions can take a list as an argument, just like len and max do. The type hint for a list is list:
def summary(numbers: list) -> str:
return f"{len(numbers)} numbers from {min(numbers)} to {max(numbers)}"
print(summary([4, 18, 9]))
ages = [34, 7, 61, 25, 12]
print(summary(ages))
3 numbers from 4 to 18
5 numbers from 7 to 61Inside the function, the parameter numbers is the list that was given in the call: first [4, 18, 9], then the list in ages.
A function can also return a list. This one reads words until an empty line and returns them all:
def read_words(prompt: str) -> list:
words = []
while True:
word = input(prompt)
if word == "":
break
words.append(word)
return words
fruit = read_words("Fruit: ")
print("In order:", sorted(fruit))
print("Alphabetically last:", max(fruit))
plum
banana
fig
(an empty line)Fruit: plum
Fruit: banana
Fruit: fig
Fruit:
In order: ['banana', 'fig', 'plum']
Alphabetically last: plumThe function builds the list in a variable of its own and returns it when the loop ends. The code that called it stores the list and goes on working with it.
What functions buy you
Read the last three lines of that program: read the fruit, print them in order, print the last one. Each line says what happens, while how it happens (the loop, the empty line, append) is tucked away in read_words. A program split into named pieces is easier to follow, and when something goes wrong, the name tells you where to look.
A function also does its job wherever it's needed. Here spread is written once and used by two other functions:
def spread(numbers: list) -> int:
return max(numbers) - min(numbers)
def weather(temperatures: list) -> str:
if spread(temperatures) > 10:
return "a day of big changes"
return "a steady day"
def judges(scores: list) -> str:
return f"the judges differ by up to {spread(scores)} points"
print(weather([12, 19, 25, 14]))
print(weather([20, 22, 21]))
print(judges([7, 9, 8, 6]))
a day of big changes
a steady day
the judges differ by up to 3 pointsIf spread had a bug, you would fix it in one place, and both functions would be right again.