Python Built-in Functions
Built-in functions are functions Python gives every program with no import. sum(), sorted(), and type() are built-in functions.
Count and find the ends
len() counts the items. min() and max() find the two ends.
scores = [8, 3, 10, 5]
print(len(scores))
print(min(scores))
print(max(scores))Total and absolute value
sum() adds a list of numbers up. abs() turns -7 into 7.
prices = [4, 6, 5]
print(sum(prices))
print(abs(-7))Rounding numbers
round() with no second argument gives a whole number. With 1, it keeps one decimal place.
print(round(2.5))
print(round(3.5))
print(round(7.86, 1))Sort and check the type
sorted() returns a new list in order. type() names the kind of value.
scores = [8, 3, 10, 5]
print(sorted(scores))
print(type(scores))id() as a picture
id() gives a number that stands for one exact value. The number changes from run to run, so we never print it.
number = id(scores)Ask help() about a function
help() prints a short guide to any built-in. Try this line in your own Python window.
help(len)Example
scores = [72, 91, 85, 91, 64]
print("Scores:", sorted(scores))
print("Count:", len(scores))
print("Lowest:", min(scores))
print("Highest:", max(scores))
print("Total:", sum(scores))
print("Average:", round(sum(scores) / len(scores), 1))Key points
- Built-in function: a function Python gives you in every program.
- You do not import it.
- Use len() to count items, and min() and max() to find the smallest and largest
- Use sum() to total numbers, and abs() to drop a minus sign
- Use sorted() to get a new list in order
- Use type() to see what kind of value you have
- Use help() to read what a function does
- id(): gives a value its identity number.
- Treat it as a picture of which value you mean.
- Shadowing: naming your own variable sum or len hides that built-in.
- Avoid built-in names for your variables.
- round(3.5) gives 4.
In this example, scores holds five exam results. sorted() prints them in order, from lowest to highest. len() counts five scores, and min() and max() find 64 and 91. sum() adds all five scores to 403. The last line divides that total by the count and rounds it to one decimal place. Six built-in functions work together in this short report.
Note
round() breaks ties to the even number.
That is why round(2.5) gives 2.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What happens if you write sum = 10 in your program?