why does filter + abs functions not give correct value

Viewed 159
numbers = list(range(-10,10))
print(numbers)
newnum = filter(abs,numbers)
print(list(newnum))
print(abs(-10))

it gives the output as below

[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10

I thought it should have given as below

[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10

Where am i going wrong ?

1 Answers

filter method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
abs(x) returns the absolute value of a number.

What is happening?

  • Each value from the numbers list is passed to abs function which is added to newnum list only if abs function returns true.
  • Since abs returns a positive number, filter takes it as true and adds that number to newnum.
  • Except, in the case when that number is 0. abs returns 0 which is false and thus is not added to the newnum list.

filter returns the elements from numbers list which results in true when passed to abs function, not the returned value from the abs function.

Related