Add 1 to a number while keeping sign in python

95 Views Asked by At

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.

3

There are 3 best solutions below

0
Cardstdani On

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]
4
sophocles 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]
0
Sören 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.