Sam Vruggink - 9 months ago 42

Python Question

I am trying to only square the positive numbers in a list. But when I try the code it squares all of them

`def squarethis(numbers):`

for n in numbers:

if n > 0:

return[n ** 2 for n in numbers]

print(squarethis([1, 3, 5, -81]))

Why does it square all numbers? The if-statement should filter the negatives out right?

Answer

Just use a single list comprehension:

```
def squarethis(numbers):
return [n ** 2 for n in numbers if n > 0]
```

What you are doing in the code your provided is checking if the first value in `numbers`

is `> 0`

, and if it is, returning your list comprehension with every value in `numbers`

squared. Instead, you can do your filtering in the list comprehension itself, and return the list.

Source (Stackoverflow)