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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With