I'm having trouble understanding the behaviour of .append()

Hi guys,

I’m not sure what I’m doing wrong, I’m working in the Python Dictionary Challenge for Hurricane Analysis and I’m stuck at the very beginning trying to debug the function to update the data. After some Googling around I found (to my surprise) that what I was trying to do was apparently successfully been done by others, which adds to my confusion.

Before building the function, I’m trying to create the code step by step in a for loop outside any def function definition.

The code

for damage in damages:
  if "M" in damage:
    print(float(damage[:-1]) * conversion["M"])

successfully iterates for every item in the list damages and prints the damage that was a string as a float multiplied by the conversion rate given (which is what we’re supposed to do, so I’m using the terminal to check that the code works line by line. So far this works. However, when I update the code to

for damage in damages:
  float_damage = []
  if "M" in damage:
    float_damage.append(float(damage[:-1]) * conversion["M"])

The terminal prints [] which tells me .append() is not doing what it should. Therefore I’m reluctant to expand the code to include the rest of the elif statements or make it a function until I get this bit right.

Some people have apparently used the same syntax for appending the values from the loop into the new list (see here and here), which makes me even more confused on why it’s not working for me.

Any hints? What am I not understanding from the usage of .append()? After all this progress I kinda thought I understood it.

your issue isn’t with append. Trace through your loop and think about what is happening each time.

You need to declare float_damage before the loop. You’re just recreating an empty one each time, so if the last loop doesn’t fulfill your if condition then it’s going to leave the loop empty

Hope that helps

1 Like

Thank you very much for that! And such a rookie mistake! Now that’s something I’ll never forget.