Record comprehension is a brief and stylish technique to create a brand new checklist by looping by way of an present one.
🧠 Primary Syntax:
[expression for item in iterable if condition]
expression
: what you need to do with every merchandisemerchandise
: the variable that takes every worth from the iterableiterable
: the gathering you are looping by way of (like checklist, vary, string)if situation
(non-obligatory): filter the objects primarily based on a situation
🔁 Record Comprehension Examples
Please observe them. Learn the code, write it down, and perceive what it’s doing. That’s the way you’ll actually profit from this course — not simply by studying, however by doing.
✅ Instance 1: Including 1 to All Numbers
nums = [1, 2, 3, 4]
squares = [n + 1 for n in nums]
print(squares)
🟢 Output:
[2, 3, 4, 5]
✅ Instance 2: Filter Even Numbers
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens)
🟢 Output:
[2, 4, 6]
✅ Instance 3: Convert to Uppercase
phrases = ['hello', 'world', 'python']
capitalized = [word.upper() for word in words]
print(capitalized)
🟢 Output:
['HELLO', 'WORLD', 'PYTHON']
Can We Use if-else in Record Comprehension?
Sure! You possibly can completely add an if-else
situation — it is like saying:
“If the situation is true, do that. In any other case, do this.”
📌 Syntax with if-else:
[do_this if condition else do_that for item in iterable]
Discover:
if-else
goes earlier than thefor
loop — not after.
✅ Instance 4: Label Even and Odd Numbers
nums = [1, 2, 3, 4, 5]
labels = ['even' if n % 2 == 0 else 'odd' for n in nums]
print(labels)
Right here, we’re checking every quantity and labeling it primarily based on whether or not it’s even or odd.
🟢 Output:
['odd', 'even', 'odd', 'even', 'odd']