Sam Vruggink Sam Vruggink - 1 year ago 63
Python Question

How to square only the positive numbers in a list?

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 Source

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.