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
- Read
[x for x in nums if x > 0]from the middle: for eachxinnums, ifx > 0, putxin the new list. - The original list
numsis not changed. - 0 is in neither list, because 0 is not greater than 0 and not less than 0. If you need it, use
x >= 0for one of them.
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.