Skip to content
Related Articles

Related Articles

Python | Reverse sign of each element in given list
  • Last Updated : 01 May, 2019

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




# 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))
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.




# 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))
Output:
[1, -2, -3, 4, -5, 6, 7]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :