Reputation: 11
So this is what I want to do:
if a > 126:
a - 94
'a' is a long list (~100 numbers) that are all numbers. I want to select the numbers that are above 126 and subtract 94 from them but keep them in the same order. is there a way to do this?
Upvotes: 1
Views: 54
Reputation: 10819
Since the list is not to long (you don't care to memory consumption), the most obvious (and very readable) way for me to solve this task would be to make a new list while iterating the first one. In this way you are sure to keep the same order and you do not modify your original list, that can be an advantage if you want to compare the two lists after...
new_list = []
for item in a:
if item > 126:
item -= 94
new_list.append(item)
Upvotes: 0
Reputation: 1125368
Use a list comprehension to build a new list:
a = [v - 94 if v > 126 else v for v in a]
The conditional expression produces v - 94
for the new value if v > 126
is true, otherwise it includes the original value unchanged.
Demo with a shorter list to keep it readable:
>>> import random
>>> a = [random.randint(80, 150) for _ in range(10)]
>>> a
[131, 133, 119, 130, 136, 129, 120, 82, 100, 126]
>>> [v - 94 if v > 126 else v for v in a]
[37, 39, 119, 36, 42, 35, 120, 82, 100, 126]
If you meant to filter out any value 126 or lower, you can still use a list comprehension:
[v - 94 for v in a if v > 126]
This selects all values over 126, and produces a new list object with just those values minus 94. This then produces a shorter list:
>>> [v - 94 for v in a if v > 126]
[37, 39, 36, 42, 35]
Upvotes: 5