Course Content
Introduction to Python
Introduction to Python
Built-in Functions
What if you were asked to find the largest number in a list? With the knowledge you've gained, you could write a loop to check if the current element is larger/smaller than the previous biggest one and update it; if not, you'd continue. But for long lists, this method can be quite time-consuming. Thankfully, there are built-in functions that can make this task more efficient. Here are a few:
min(x, y, ...)
- Returns the smallest value amongx, y, ...
;max(x, y, ...)
- Returns the largest value amongx, y, ...
;abs(x)
- Gives the absolute value ofx
;round(x, n)
- Rounds the numberx
ton
decimal places;pow(x, n)
- Raisesx
to the power ofn
.
For instance, suppose we want to calculate the population density for a set of countries in the countries
list. To do this, we'd divide the population by the area. Here's how it's done:
# Initial data countries = [["USA", 9629091, 331002651], ["Canada", 9984670, 37742154], ["Germany", 357114, 83783942], ["Brazil", 8515767, 212559417], ["India", 3166391, 1380004385]] # Iterating over external list for i in range(len(countries)): if type(countries[i]) is list: # Computing population density for a country pop_dens = countries[i][2]/countries[i][1] print(countries[i][0], pop_dens, 'people per km²')
In the example above, our list had 5 nested sub-lists. We looped through the main list and checked if each item was a list. If it was, we divided the third item (population) by the second item (area).
However, the results were not very reader-friendly since they had more than 10 decimal places. To make them more readable, we can use the round()
function to reduce them to just 2 decimal places. Remember, this function takes two arguments: the first is the number you want to round, and the second specifies how many decimal places you want to keep.
# Initial data countries = [["USA", 9629091, 331002651], ["Canada", 9984670, 37742154], ["Germany", 357114, 83783942], ["Brazil", 8515767, 212559417], ["India", 3166391, 1380004385]] # Iterating over external list for i in range(len(countries)): if type(countries[i]) is list: # Computing population density for a country pop_dens = round(countries[i][2]/countries[i][1], 2) print(countries[i][0], pop_dens, 'people per km²')
As you can see, the revised result is much clearer and easier to understand.
Thanks for your feedback!