This tutorial will discuss about unique ways to convert all positive numbers to negative in Python list.
Table Of Contents
Using List Comprehension
Iterate over all numbers in Python List using a List comprehension. During iteration, for each number check if it is greater than zero or not. If yes, then multiply that number with -1 to make it negative.
This List comprehension will give a list of negative numbers only, but converting all the positive numbers in list to negative.
Let’s see the complete example,
Frequently Asked:
listOfNumbers = [11, -2, -9, -10, -23, 33, 56, -67, -90] # Convert all positive numbers to negative listOfNumbers = [num*-1 if num > 0 else num for num in listOfNumbers] print(listOfNumbers)
Output
[-11, -2, -9, -10, -23, -33, -56, -67, -90]
Using map() function
Apply a lambda function to all elements of List in Python using the map() function. This Lambda function will accept a number as an argument, and if that number is positve, then returns a negative version of the number. Whereas, if number is already negative, then it returns the negative number without any change.
The map() function, will return a mapped object containing all the negative numbers. Then we can convert that back to list. This way all positive numbers in list will be converted into negative numbers.
Let’s see the complete example,
Latest Python - Video Tutorial
listOfNumbers = [11, -2, -9, -10, -23, 33, 56, -67, -90] # Convert all positive numbers to negative listOfNumbers = list(map(lambda x: x*-1 if x > 0 else x, listOfNumbers)) print(listOfNumbers)
Output
[-11, -2, -9, -10, -23, -33, -56, -67, -90]
Using NumPy Array
Convert list to a NumPy Array, then apply minus operator on numpy array to inverse the sign of all numbers. But this will make,
* All positive numbers negative
* All negative numbers positive.
This is not our exact requirement. But this is good to know, incase you encounter this changed requirement in future.
Let’s see the complete example,
import numpy as np listOfNumbers = [11, -2, -9, -10, -23, 33, 56, -67, -90] # create a numpy array from list arr = np.array(listOfNumbers) # Convert all positive numbers to negative arr = -arr # Convert numpy array to list again listOfNumbers = arr.tolist() print(listOfNumbers)
Output
[-11, 2, 9, 10, 23, -33, -56, 67, 90]
Summary
We learned about different ways to convert all positive numbers in a Python List into negative numbers. Thanks.
Latest Video Tutorials