0

I am looking to edit elements in a list bar one element - I am wondering how to do so? I am making one element go up, the one selected, and the others to go down. I have worked out how to do the first bit, just not the second. Here is my code so far

score = [70,60,80]
action = ["one person off", 2, 200]

def take_action(score, action):
    x = action[1]
    if action[0] = "one person off":
        score[x] += 30

I am looking for 80 to go to 110 and the others to go down by 10 each.

Any help would be greatly appreciated!

2
  • Do you mean to add an else: part to the if statement with score[x] -= 10 in it? Commented Nov 15, 2021 at 16:29
  • @mkrieger1 no, I want it to both happen, so want score[x] += 30 and the something underneath that would represent elements that are not score[x] going down by 10 - sorry new to stack overflow Commented Nov 15, 2021 at 16:32

2 Answers 2

1

You could implement the action as loop:

for i,s in enumerate(score):
    score[i] = s+30 if i == x else s-10
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much! this has worked spot on!
0

You can use a list comprehension:

score = [value+30 if i==x else value-10 for i,value in enumerate(score)]

This will give you back a new list, with the xth element increased by 30 and the others decreased by 10.

In order to modify the list that was passed in (rather than creating a new local variable named score) you would need to perform the assignment slightly differently:

score[:] = [value+30 if i==x else value-10 for i,value in enumerate(score)]

3 Comments

This will not update the score variable passed as parameter because it creates a new list in a local variable (also named score).
@AlainT. Ah, you're correct. I was assuming there was a return that wasn't shown, but that may be a bad assumption.
you could assign score[:] = ... instead and it would work.

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.