How can I go from:
lst = [-2, -4, 5, 7]
to:
lstmod = [-3, -5, 6, 8]
I want to add 1 (or a given x value) to each number's magnitude, while keeping the sign. I also want the result to be a list with the same order.
How can I go from:
lst = [-2, -4, 5, 7]
to:
lstmod = [-3, -5, 6, 8]
I want to add 1 (or a given x value) to each number's magnitude, while keeping the sign. I also want the result to be a list with the same order.
You can use list comprehension as follows:
lst = [-2, -4, 5, 7]
lst = [(i-1) if i < 0 else (i+1) if i > 0 else 0 for i in lst]
print(lst)
Output:
[-3, -5, 6, 8]
IIUC, you can use:
lst = [-2, -4, 5, 7]
lstmod = [num+1 if num > 0 else num-1 for num in lst]
prints:
[-3, -5, 6, 8]