Https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-strings/projects/ds-python-strings-project

Hi, wrt to the Medical Insurance Project in the Python Strings Exercise Im confused as to why the following code is only giving the last individual’s output.Any help is welcome, thanks in advance!
Code-
for records in medical_records_clean:

info =’{} is {} years old with a BMI of {} and an insurance cost of ${}.’

info = info.format(records[0],records[1],records[2],records[3])

print(info)
Output-
Average Insurance Cost: 8390.7
ISAAC VU is 34 years old with a BMI of 24.8 and an insurance cost of $7045.0.

Hello! I would have to see the full code to give a proper explanation, but I would assume that the first four items in the records list are all to do with the one person.


This is the link to the full code. Thanks for your help.

It is because you are going for every item(which is also a list) in the medical_records_clean list… So the records[0] refers to the first item of the first nested list in medical_records_clean. Then the next iteration it would refer to the first item of the second list in medical_records_clean, and so on.

Im sorry I dont get it but either way, how can I fix the code?

How do you mean fix the code? What do you want it to do?


I will try to explain it again:
Note: medical_records_clean is a list with multiple nested lists in it. Its structure would look like this: [[], [], [], []]

for records in medical_records_clean:#loops through each nested list
#in the medical_records_clean list. Each sub list is referred to as records
#for the purpose of this loop
  info ='{} is {} years old with a BMI of {} and an insurance cost of ${}.'
#this just sets the info variable up with the correct structure.
  info = info.format(records[0],records[1],records[2],records[3])
#This line formats the variables into the info structure. Then, each 
#iteration, the records variable refers to a different nested list within
#medical_records_clean.
print(info)#This is outside the loop, and, therefore only runs when the
#loop finishes. It prints the last value of info-the value it took on the
#last iteration.

I hope this helps!

1 Like