Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking absolute values of a list of numbers

I have checked similar branches in Stock, however all use some prepared libraries; that's not what i want.

I wanted to create a function that would take a list of numbers, take their absolute values and print the modified list. Here is my code:

def abs(array):
    for member in array:
        if member < 0:
            member = member * (-1)
        else:
            member = member

    print(array)

But it prints the original list. For example:

abs([1, -34, 23, 2342, 52, -3, -12, -123, -23])

Gives:

[1, -34, 23, 2342, 52, -3, -12, -123, -23]

Process finished with exit code 0

 
like image 933
Curious Scientist Avatar asked Jan 25 '23 11:01

Curious Scientist


1 Answers

The problem is with the loop you are using , Trying modifying it this way

def abs1(array):
    for i in range(len(array)):
        if array[i] < 0:
             array[i] = array[i] * (-1)
    print(array)

The reason is the loop you were previously using was just for accesing list elements but not giving you reference to change anything in list I solved it with using indexes on list.

like image 134
KnightKnight Avatar answered Jan 31 '23 21:01

KnightKnight