Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate40 min

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.

List comprehension parts expression for in if
python
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

python
lst = [4, 3, 7, -2, 6, 3]
newlst = []
for val in lst:
    newlst.append(val * 2)
print(newlst)

Same result in one line:

python
lst = [4, 3, 7, -2, 6, 3]
newlst = [val * 2 for val in lst]
print(newlst)

Output:

code
[8, 6, 14, -4, 12, 6]
Four three seven minus two each doubled

Reading tokens — split()

Classroom programs often print a prompt and call input().split().

python
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:

python
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).

Space separated text split then float each token

You can also keep strings:

python
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.

python
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)
Keep positives ten and twenty-two drop negatives and zero
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):

python
[val * 2 for val in [4, 3, 7]]

With if, only matching items enter the new list:

python
[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

  1. Change * 2 to * 3 and confirm 4 becomes 12.
  2. Change the positive filter to >= 0 — 0 should appear.
  3. Use int(val) instead of float(val) on raw and 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