How to square only the positive numbers in a list?
<p>I am trying to only square the positive numbers in a list. But when I try the code it squares all of them</p>

<pre><code>def squarethis(numbers):
for n in numbers:
    if n &gt; 0:
        return[n ** 2 for n in numbers]

print(squarethis([1, 3, 5, -81]))
</code></pre>

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

<p>Just use a single list comprehension:</p>

<pre><code>def squarethis(numbers):
    return [n ** 2 for n in numbers if n &gt; 0]
</code></pre>

<p>What you are doing in the code your provided is checking if the first value in <code>numbers</code> is <code>&gt; 0</code>, and if it is, returning your list comprehension with every value in <code>numbers</code> squared. Instead, you can do your filtering in the list comprehension itself, and return the list.</p>

python list math int square