Lists are mutable - we can change their elements with
l = 100. Python provides an alternative to lists -
tuple, that guarantees that the individual elements are not going to change. It’s mainly used for very related pieces of information such that when one element is updated, the whole information is changed and therefore the whole tuple should be updated.
box = (20, 30, 50) print('height:', box) print('width:', box) print('depth:', box)
Note that the only difference here is that we use parentheses
()instead of brackets
like we used to do for lists. We could even omit the parentheses and just use
box = 20, 30, 50, which would have resulted in exactly the same tuple.
Tuples are not modifiable. They don’t have an
adda method to add elements. If we try to change the box height, we need to change the whole tuple:
box = (20, 30, 50) box = 10 # TypeError: 'tuple' object does not support item assignment box = (10, 30, 50) # OK box = 10, 30, 50 # OK
There is also an easy way of unpacking the tuple elements:
box = 20, 30, 50 height, width, depth = box print('height:', height) print('width:', width) print('depth:', depth)
height, width, depth = 20, 30, 50 print('height:', height) print('width:', width) print('depth:', depth)
Did you know that you could read multiple inputs with a single line of code?
name, height = input(), int(input())
This is possible thanks to tuples and the unpacking of values.
You are asked to read the records for
npatients and report their stats. This time the records include their names and the weight of each patient. You are asked to report the average of all the patients, and for each patient how much above or below the average they are.
The first line of the input contains a single integer
n- the number of patients. The next lines contain the name of the patient followed by their weight on the next line.
The program should first print the average weight, and then the names of the patients, followed by a colon, and
X above averageif the weight is above or equal to the average, and
X below averageif it’s below.
3 Anna 50 Bob 80 Simon 71
67 Anna: 17 below average Bob: 13 above average Simon: 4 above average