Lesson 02
List Comprehension — Expression, split(), and if Filters
Build Python lists in one line: cast tokens with split, double values, and keep positives with an if clause in a list comprehension.
What you will learn
- The list syntax:
[expression for name in iterable if cond] - Expression as type casting or math
- The
split()pattern for space-separated values - Filtering with
if(positives only) - How this replaces a for loop plus
append
This continues from the Comprehensions overview.
The big idea
A list comprehension builds a new list from an iterable in one expression.
listobj = [expression for varname in iterable_object if test_cond]From the teaching notes: expression is either type casting or a mathematical expression.
Traditional loop vs comprehension
lst = [4, 3, 7, -2, 6, 3]
newlst = []
for val in lst:
newlst.append(val * 2)
print(newlst)Same result in one line:
lst = [4, 3, 7, -2, 6, 3]
newlst = [val * 2 for val in lst]
print(newlst)Output:
[8, 6, 14, -4, 12, 6]Reading tokens — split()
Classroom programs often print a prompt and call input().split().
print("Enter List of values separated by space:")
lst = [float(val) for val in input().split()]In the MahiDev playground, input() would block. Use a string with the same comprehension:
raw = "10 2 22 50 10 4 55 -3 0 22"
lst = [float(val) for val in raw.split()]
print("content of lst", lst)split() with no argument splits on whitespace. Each token is cast with float(val).
You can also keep strings:
raw = "10 2 22"
lst = [str(val) for val in raw.split()]
print(lst)
print(type(lst))Filter with if — positives only
Keep values greater than 0. Zeros and negatives are dropped.
tokens = "10 -3 0 22 5 -8 7"
pslist = [int(value) for value in tokens.split() if int(value) > 0]
print("List of +ve Values=", pslist)| Token | int(value) > 0 |
Result |
|---|---|---|
| 10 | True | Keep |
| -3 | False | Drop |
| 0 | False | Drop |
| 22 | True | Keep |
This is the same idea as filter(), written as a list comprehension.
Optional if
Without if, every item is kept (and transformed):
[val * 2 for val in [4, 3, 7]]With if, only matching items enter the new list:
[val * 2 for val in [4, 3, 7] if val > 0]Common mistakes
Calling input() in the playground — it cannot wait for the keyboard. Use a string + split().
Filter in the expression — if goes after the for clause, not inside the math.
Forgetting list brackets — {x for x in nums} is a set, not a list.
Interview cheat sheet
| Question | Answer |
|---|---|
| List brackets? | [ ] |
| Cast tokens from text? | [float(v) for v in text.split()] |
| Double each value? | [v * 2 for v in lst] |
| Positives only? | if int(v) > 0 |
| Loop equivalent? | empty list + append |
Practice in the playground
- Change
* 2to* 3and confirm4becomes12. - Change the positive filter to
>= 0—0should appear. - Use
int(val)instead offloat(val)onrawand compare types.
Next: Set comprehension.
Loading playground…
Check your understanding
List comprehension quiz
What is the output of `[val * 2 for val in [4, 3, 7, -2, 6, 3]]`?
1 / 10