Taking absolute values of a list of numbers

Viewed 502

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

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

Try :

import numpy as np

array= ...

np.abs(np.array(array))

numpy is very powerful and fast, learn to use it asap.

EDIT since the problem is how to do a function on each element of a list and wrap those results in a list of the same length :

Two solutions come to mind :

  • hardcore python style :
[x if x<0 else -x for x in array]

the brackets say I want a list, inside I write the function and I say where to find the parameters to my function.

[abs(x) for x in array]
[f(x) for x in array] # for any defined f that can handle every element of array
  • map(lambda x : f(x), array)

you create a mapping on the elements of array. To those elements, you apply lambda. lambda is a way to define a function locally, very locally.

list(map(lambda x : abs(x),array))

finally you make a list from the mapping, to retrieve the result. If you don't, it will stay as an abstract, the definition of a relation between array and something that is yet to be instantiated.

There are two mistakes with your code:

  1. abs is a preexisting Python function. Never name your own functions after a preexisting one; it can cause unexpected behavior.

  2. You shouldn't modify parameters in a function. Instead, create a new array and return it.

Below is the corrected code:

def list_abs(array):
    new_array = []
    for member in array:
        if member < 0:
            new_array.append(member * (-1))
        else:
            new_array.append(member)
    return new_array

array = [2, 3, 4, -5, -6, 7, -8]
print(list_abs(array))
# Prints [2, 3, 4, 5, 6, 7, 8]

In Python, if you use a for in this way the value won't be assigned into the array. Try this code.

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

print(array)
Related