List help , modifiying values in a list

I have the following list …

Test = [5.3, 5.3, 33.0, 15.3, 7.2, 7.2, 457.2, 439.5, 438.0, 427.1, 409.4, 408.0, 408.0, 408.0, 408.0, 408.0, 408.0, 408.0, 408.0, 408.0, 397.2, 379.5, 378.0, 367.2, 349.5, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0, 348.0]

I need to modify all the values if one value is over 400.

How could this be achieved with list comprehension. I need to keep all other values and only modify values after 400.

 if maxvalue > 400:
        print (maxvalue,'this is max value')
  
        it = itertools.dropwhile(lambda x: x != maxvalue, Test)
        next(it)
        for num in it:
            print(num-108)  
            fixedo = num-108

This code partially works but creates a new list with only the new modified values.

This modifies both the first value in the list over 400 itself, and all those after it.

seen_item_over_400 = False
for i, item in enumerate(list_):
    if not seen_item_over_400:
        if item > 400:
            seen_item_over_400 = True
        else:
            continue
    # Or whatever the modification is.
    list_[i] -= 108
2 Likes

Thanks so much, works like a dream

Hello,

The way that I interpreted this (correct me if I am wrong), is that you want to modify the values in the list ONLY if they are greater than 400 else do nothing. Is this correct?

Ok, per your requirement of achieving this by way of a list comprehension, you may do the operation concisely like this (for demo purposes, I am deducting 100 from any value over 400).

Test = [x - 100 if x > 400 else x for x in Test]
print(Test)  # Print and verify results

In the list comprehension, you may change the x - 100 operation to your requirement.

1 Like

Hi thanks for the reply, sorry if not clear.

It was if there was a value ~ 400 , then the 400 value and every subsequent value should then be altered.