Python | Reverse sign of each element in given list

Given a list of integers, write a Python program to reverse the sign of each element in given list.

Examples:

Input : [-1, 2, 3, -4, 5, -6, -7]
Output : [1, -2, -3, 4, -5, 6, 7]

Input : [-5, 9, -23, -2, 7]
Output : [5, -9, 23, 2, -7]

 

Methods #1 : List comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Convert positive 
# list integers to negative and vice-versa
def Convert(lst):
    return [ -i for i in lst ]
  
# Driver code
lst = [-1, 2, 3, -4, 5, -6, -7]
print(Convert(lst))

chevron_right


Output:

[1, -2, -3, 4, -5, 6, 7]

Methods #2 : Using numpy
The Python module, Numpy, can also be used which is the most pythonic way to solve the given problem. The list is first converted to numpy array and then, the negative of the array is returned, which is finally converted to list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Convert positive 
# list integers to negative and vice-versa
import numpy as np
  
def Convert(lst):
    lst = np.array(lst)
    return list(-lst)
      
# Driver code
lst = [-1, 2, 3, -4, 5, -6, -7]
print(Convert(lst))

chevron_right


Output:

[1, -2, -3, 4, -5, 6, 7]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.