...

/

List Comprehensions Using Conditions

List Comprehensions Using Conditions

Learn how to use a list comprehension with a condition.

We'll cover the following...

Imagine you want to find the square root of every value in a list, but you want to ignore any negative values so that they don’t even appear in the output list. Here is how you might do it with a loop:

Press + to interact
import math
k = [-1, 16, 9, -4, 0, 25]
a = []
for x in k:
if x>=0:
a.append(math.sqrt(x))
print(a)

You ...