0

I'm having trouble setting a list at a certain index to a specified value. For example:

healths[index].split(",")[anotherIndex] = 0

This code runs but doesn't change the value. The reason I'm not just moving this to a list and going through these hoops with indexing a split list is because the first list, "healths" is also a split list. This means the amount of lists within is not a set value, so I could have 1 string in healths or I could have 4 strings in healths. If anyone can help with this it would be much appreciated. Here is another example highlighting what I'm trying to do:

strHealth = "1,8,4,3,/11,12,/"
healths = strHealth.split("/")
ct = int(input("Enter the creature type you're targeting: ")) - 1
cn = int(input("Enter the number of the creature you're targeting: ")) - 1
damage = int(input("Enter the amount of damage dealt: "))
healths[ct].split(",")[cn] = str(int(healths[ct].split(",")[cn]) - damage)

I tried setting the initial healths[ct].split(",")[cn] to an integer but that gave me a "cannot assign to function call here" error. I also double checked on how to change values in a list in python. This has me a bit stumped at the moment.

2
  • 1
    split() returns a new list. Your last line of code creates this list but does not assign it to a variable. The list will disappear as soon as the line of code is complete. So when you modify an element of that list, Python will change the modified index ([cn]), but there is no way to see that because the whole list immediately disappears. Commented Mar 22 at 2:24
  • Why are you storing everything a strings? Surely it would be much easier to use a list of lists of ints? Commented Mar 22 at 13:51

1 Answer 1

0

Now that i know the split function creates a new list that can't be saved, I found a new way of changing the values.

health_list = healths[ct].split(",")
health_list[cn] = str(int(health_list[cn]) - damage)
healths[ct] = ",".join(health_list)

I need to just make a temporary list as a placeholder then join the list back together with the new value.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.