Python Lists: Medical Insurance Project Question

I have finished this module and my code was successful, but I wanted to make the calculations for the difference (one of the extra exercises at the end) smaller, so I added the calculations to the creation of a list but it doesn’t like the Syntax, and I cannot understand why.

Originally, I had the following line for each person:
maria_dif = maria_insurance_cost - insurance_cost[0]

I did this for each person, referencing the position in the insurance_cost list where I knew their information resided. These four variables were added to a list called insurance_difference and then printed out as below:

insurance_difference = [maria_dif, rohan_dif, valentina_dif, akira_dif]
insurance_cost_difference = (list(zip(names, insurance_difference)))
print(insurance_cost_difference)

I then tried to combine it all together in a single statement and it returned a SyntaxError:

insurance_difference = [(maria_dif = maria_insurance_cost - insurance_costs[0]), (rohan_dif = rohan_insurance_cost - insurance_costs[1]), (valentina_dif = valentina_insurance_cost - insurance_costs[2]),
(akira_dif = akira_insurance_cost - insurance_costs[3])]

What have I missed? I thought you could do the calculations inside the code for the insurance_difference list.

You can evaluate expressions (+, - etc.) but you can’t use assignments (so no a = b ).

If you’re adding these elements to a list do you need to name them too? If so consider dictionaries if they’re been introduced but no worries if not, they’ll pop up soon enough.

1 Like

Thank you! I haven’t seen dictionaries yet, I was just wanting to play around with the new thing I learned and thought I was being clever. :smiley:

1 Like

There’s technically a way to do this since python 3.8 though it has somewhat limited use and it won’t help you in this case or with lessons in general, so see below only if you’re very curious-

I am the walrus (operator)

Assignment expressions := were introduced with Python 3.8 though it’d be considered bad practice to use it inside a list literal (see the link for some neat examples). I don’t think many lessons run python with 3.8+ and there’s not many places where it actually enhances readability so it’s not really useful to you at the moment but it’s an interesting addition.

For some details and some examples see-
PEP 572 -- Assignment Expressions | Python.org
6. Expressions — Python 3.9.1 documentation

1 Like