Python | Reverse sign of each element in given list
Last Updated :
24 Mar, 2023
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
def Convert(lst):
return [ - i for i in lst ]
lst = [ - 1 , 2 , 3 , - 4 , 5 , - 6 , - 7 ]
print (Convert(lst))
|
Output:
[1, -2, -3, 4, -5, 6, 7]
Time Complexity: O(n).
Space Complexity: O(1).
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
import numpy as np
def Convert(lst):
lst = np.array(lst)
return list ( - lst)
lst = [ - 1 , 2 , 3 , - 4 , 5 , - 6 , - 7 ]
print (Convert(lst))
|
Output:
[1, -2, -3, 4, -5, 6, 7]
Time Complexity: O(n).
Space Complexity: O(1).
Method #3 : Using startswith() and replace() methods
Python3
lst = [ - 1 , 2 , 3 , - 4 , 5 , - 6 , - 7 ]
nl = list ( map ( str , lst))
res = []
for i in nl:
if (i.startswith( "-" )):
i = i.replace( "-" , "")
res.append( int (i))
else :
i = "-" + i
res.append( int (i))
print (res)
|
Output
[1, -2, -3, 4, -5, 6, 7]
Time Complexity: O(n).
Space Complexity: O(n).
Method #4: Using map function and neg operator methods
Python
from operator import neg
lst = [ - 1 , 2 , 3 , - 4 , 5 , - 6 , - 7 ]
nl = list ( map (neg, lst))
print (nl)
|
Output:
[1, -2, -3, 4, -5, 6, 7]
Time Complexity: O(n).
Space Complexity: O(1).
Method #5 : Using find(),int()+slicing
Approach
Convert integer list to string list using list(),map(),str
- Initiate a for loop to traverse string list
- For each string if there is – sign at the beginning slice string 1 to end , convert it to integer and append to output list
- If not append – sign at the beginning, convert to integer and append to output list
- Display output list
Python3
lst = [ - 1 , 2 , 3 , - 4 , 5 , - 6 , - 7 ]
nl = list ( map ( str , lst))
res = []
for i in nl:
if (i.find( "-" ) = = 0 ):
res.append( int (i[ 1 :]))
else :
i = "-" + i
res.append( int (i))
print (res)
|
Output
[1, -2, -3, 4, -5, 6, 7]
Time Complexity : O(N) N – number of elements in list
Auxiliary Space : O(N) N – number of elements in list
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...