TalentJR

🐍 Python for kids · Class 7 · Lesson 7 of 18 · Free

List Comprehensions – Build Lists in One Line

⏱ About 30 minutes · ▶ run real Python here — nothing to install · no sign-in

In this lesson you will

  • Build a new list from an old one with a list comprehension.
  • Filter items with if, and choose between two values with if-else.
  • Use comprehensions with input(), sum(), len() and lists of lists.

Your teacher wants every mark in the class increased by 5 grace marks. A loop with append() takes four lines. A list comprehension does the same job in one clear line.

What is a list comprehension in Python?

Very often we make an empty list, loop over another list, and append() a changed item each time.

A list comprehension packs that whole pattern into one line inside square brackets.

Read it from the middle: for each p in prices, put p plus tax into the new list.

Below, both ways add 18% GST to shop prices. Watch how the two answers match.

🎬 How Python thinks — step 1 of 16Python is about to run line 1
▶prices = [100, 250, 40]
2with_tax = []
3for p in prices:
4 with_tax.append(p + p * 18 // 100)
5print(with_tax)
6quick = [p + p * 18 // 100 for p in prices]
7print(quick)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
[118, 295, 47]
[118, 295, 47]

💡 The pattern is always [expression for item in list]. The expression decides what goes into the new list.

How do I filter a list with if in a comprehension?

Add an if at the end, and only the items that pass the test are kept.

Items that fail the test are simply skipped. They do not appear in the new list at all.

Here we keep only the students who scored 35 or more, the pass mark in many Indian schools.

🎬 How Python thinks — step 1 of 10Python is about to run line 1
▶marks = [78, 22, 91, 34, 56]
2passed = [m for m in marks if m >= 35]
3print("Passed marks:", passed)
4print("How many passed:", len(passed))
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Passed marks: [78, 91, 56]
How many passed: 3

💡 The new list can be shorter than the old one. Filtering never changes the original list.

Can a comprehension use functions and string methods?

The expression part can be any Python you know: a method, a function call or a sum.

This is handy for cleaning data. Below, upper() fixes names and len() counts letters.

The last line turns typed text like "45 78 90" into a list of real numbers. split() cuts the text at spaces.

🐍 Python — you can edit this code
Output
['RIYA', 'ARJUN', 'MEERA']
[4, 5, 5]
Enter marks: 45 78 90
[45, 78, 90] Total: 213

💡 Without int(), the list would hold text like "45". You cannot add text to get a total.

How do I use if-else inside a list comprehension?

Sometimes you want to keep every item but change it in two different ways.

Then the if-else goes at the front, before for. It picks one of two values for each item.

Remember the rule: an if alone at the end filters. An if-else at the front chooses.

🎬 How Python thinks — step 1 of 15Python is about to run line 1
▶marks = [78, 22, 91, 34]
2result = ["Pass" if m >= 35 else "Fail" for m in marks]
3print(result)
4sizes = ["big" if n > 10 else "small" for n in range(8, 13)]
5print(sizes)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
['Pass', 'Fail', 'Pass', 'Fail']
['small', 'small', 'small', 'big', 'big']

How do I build lists from range() and flatten a list of lists?

A comprehension can loop over range() too. This makes number patterns like tables very quick.

It can also have two for parts. They work like a loop inside a loop, read from left to right.

This is useful to flatten a list of lists into one simple list. You will meet nested data in the next lesson.

🐍 Python — you can edit this code
Output
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
[1, 4, 9, 16, 25]
['Ravi', 'Isha', 'Sam', 'Anu', 'Dev']

When should I use a list comprehension, and when a normal loop?

Use a comprehension when you are building a new list. It is short, fast and easy to read.

Comprehensions work nicely with sum(), max(), min() and len(). Here we count runs from boundaries only.

If you need to print things or do many steps per item, use a normal loop. Clear code beats clever code.

🐍 Python — you can edit this code
Output
Boundaries: [4, 6, 4]
Runs from boundaries: 14
Dot balls: 1

💡 If a comprehension becomes longer than one screen line, split the job into a normal loop.

🤔 Predict the output

Think like Python: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

print([n * 2 for n in [1, 2, 3]])

Question 2. What does this print?

words = ["hi", "india", "ok", "cricket"]
print([w for w in words if len(w) > 2])

Question 3. What does this print?

print(["even" if n % 2 == 0 else "odd" for n in range(1, 4)])

🧩 Your challenge

Make an over summary for a cricket match. Ask for the runs of 6 balls on one line, like "1 4 0 6 2 4". Use list comprehensions to make a list of numbers and a list of boundaries (4s and 6s). Print the runs, the boundaries and the total runs in the over.

Expected output (with the inputs given):
Runs on each ball: 1 4 0 6 2 4
Runs: [1, 4, 0, 6, 2, 4]
Boundaries: [4, 6, 4]
Total runs in the over: 17
🐍 Python — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

marks = [78, 22, 91]
result = [m for m in marks if m >= 35 else 0]
print(result)

SyntaxError: invalid syntax

✅ Right

marks = [78, 22, 91]
result = [m if m >= 35 else 0 for m in marks]
print(result)

An if-else must go at the front, before for. Only a lone if, with no else, goes at the end.

❌ Wrong

marks = ["45", "90", "60"]
print(sum([m for m in marks]))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

✅ Right

marks = ["45", "90", "60"]
print(sum([int(m) for m in marks]))

The items are text, not numbers. Use int(m) in the expression to change each one before adding.

❌ Wrong

squares = [n * n for n in range(4)]
print(squares)
print(n)

NameError: name 'n' is not defined

✅ Right

squares = [n * n for n in range(4)]
print(squares)
print(squares[-1])

The loop variable of a comprehension lives only inside the brackets. Use the new list, not n, afterwards.

📌 Remember

  • A list comprehension builds a new list in one line: [expression for item in list].
  • An if at the end filters: only items that pass the test are kept.
  • An if-else at the front chooses one of two values for every item.
  • The expression can use methods and functions, like upper(), len() or int().
  • Two for parts work like a loop inside a loop, for example to flatten a list of lists.
  • Use a normal loop when the job has many steps or needs print().

Finished the quiz and the challenge?

Questions students ask

Is a list comprehension faster than a for loop?

Usually it is a little faster, because Python does the appending for you. But choose it for clarity, not only for speed.

Does a list comprehension change the original list?

No. It always makes a brand new list. The old list stays exactly as it was.

Why does the if go at the end sometimes and at the front other times?

An if at the end decides which items to keep. An if-else at the front decides what value each item becomes.

Can I make a dictionary or set in the same way?

Yes. Python also has dictionary and set comprehensions with curly brackets. Master list comprehensions first, and the others feel easy.