PythonMastery

List comprehension with if condition in Python

Use a list comprehension with an if clause to keep only the items you want: positive numbers, negative numbers, or words of a certain length.

A list comprehension builds a new list from an existing one in a single line. An if at the end keeps only the items for which the condition is true.

The program

python
nums = [4, -2, 0, 7, -9, 3, -1]

positive = [x for x in nums if x > 0]
negative = [x for x in nums if x < 0]

print("Positive:", positive)
print("Negative:", negative)
output
Positive: [4, 7, 3]
Negative: [-2, -9, -1]

How it works

The same code with a normal loop needs four lines:

python
nums = [4, -2, 0, 7, -9, 3, -1]

positive = []
for x in nums:
    if x > 0:
        positive.append(x)

print(positive)
output
[4, 7, 3]

Changing the items as well

The part before for can change each item that passes the test. This keeps the long words and makes them upper case:

python
words = ["cat", "python", "list", "comprehension", "if"]

long_words = [w.upper() for w in words if len(w) > 4]
print(long_words)
output
['PYTHON', 'COMPREHENSION']

Related programs: Filter even numbers from a list, if else in a list comprehension.

Learn the idea: Comprehensions: Lists, Dicts, Sets, Generators, Lists & Sequences