tuple

Lists are mutable - we can change their elements with l[1] = 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[0])
print('width:', box[1])
print('depth:', box[2])
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 append or add a method to add elements. If we try to change the box height, we need to change the whole tuple:
box = (20, 30, 50)
box[0] = 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)

Challenge

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 n patients 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 average if the weight is above or equal to the average, and X below average if it’s below.
Input
Output
3 Anna 50 Bob 80 Simon 71
67 Anna: 17 below average Bob: 13 above average Simon: 4 above average
 

Constraints

Time limit: 2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue