Search code examples
pythonnumbersnegative-number

How to convert positive numbers to negative in Python?


I know that abs() can be used to convert numbers to positive, but is there somthing that does the opposite?

I have an array full of numbers which I need to convert to negative:

array1 = []
arrayLength = 25
for i in range(arrayLength):
   array1.append(random.randint(0, arrayLength)

I thought perhaps I could convert the numbers as they're being added, not after the array is finished. Anyone knows the code for that?

Many thanks in advance


Solution

  • If you want to force a number to negative, regardless of whether it's initially positive or negative, you can use:

        -abs(n)
    

    Note that integer 0 will remain 0.