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.
On
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]
On
Slight variation on @Cardstdani's and @sophocles' answer:
lst = [-2, -4, 5, 7]
lstmod = [ num + sign(num) for num in lst ]
where sign is any of the functions from this question.
You can use list comprehension as follows:
Output: