20

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 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

Aya Noaman
  • 334
  • 1
  • 2
  • 12

5 Answers5

34

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.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
18

-abs(n) is a really good answer by Tom Karzes earlier because it works whether you know the number is negative or not.

If you know the number is a positive one though you can avoid the overhead of a function call by just taking the negative of the variable:

-n 

This may not matter much at all, but if this code is in a hot loop like a gameloop then the overhead of the function call will add add up.

>>> timeit.timeit("x = -abs(y)", setup="y = 42", number=5000)
0.0005687898956239223
>>> timeit.timeit("x = -y", setup="y = 42", number=5000)
0.0002599889412522316
Induane
  • 1,774
  • 2
  • 13
  • 11
5

I believe the best way would be to multiply each number by -1:

def negativeNumber(x):
    neg = x * (-1)
    return neg
zgebac26
  • 81
  • 9
3

You are starting with positive numbers, so just use the unary - operator.

arrayLength = 25
array1 = [-random.randint(0, arrayLength) for _ in arrayLength]
chepner
  • 497,756
  • 71
  • 530
  • 681
-2

This will also go good

import random
array1 = []
arrayLength = 25
for i in range(arrayLength):
   array1.append((random.randint(0, arrayLength)*-1))
Divyessh
  • 2,540
  • 1
  • 7
  • 24