1

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.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102

3 Answers3

2

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]
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
0

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]
sophocles
  • 13,593
  • 3
  • 14
  • 33
0

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.

Sören
  • 1,803
  • 2
  • 16
  • 23