STR Coding Club logo STR Coding ClubLearn to code, together
Python and Practice

Python List Comprehension Practice With Five Exercises

A student in my Tuesday group handed me a line of code last spring that was 118 characters long, had two for clauses and an if in the middle, and did something with a list of exam marks. She could not explain it.

A laptop screen showing a short Python list comprehension beside the longer for loop version written in a notebook

A student in my Tuesday group handed me a line of code last spring that was 118 characters long, had two for clauses and an if in the middle, and did something with a list of exam marks. She could not explain it. She had copied the shape from a tutorial, changed the variable names until the error messages stopped, and assumed that meant she understood it. Two weeks later she could not debug her own program because she could not read her own line.

That is the real problem with list comprehensions. They are not hard to type. They are easy to type badly, and the damage shows up later, when something breaks and you cannot step through a single line in your head. Good Python list comprehension practice is therefore not about writing clever one liners. It is about seeing which loops collapse cleanly, which ones should be left alone, and being able to read the collapsed version back out loud.

What a Comprehension Actually Replaces

Almost every comprehension you will ever write replaces the same three line pattern: make an empty list, loop over something, append to the list.

Written out, that pattern is: results = [] then for word in words: then results.append(word.upper()). The comprehension version is results = [word.upper() for word in words]. Read it in that order and it stays readable: the expression first, then where the items come from.

The reading trick I give beginners is to say it as an English sentence from the middle out. For the line above, that is "for every word in words, give me word dot upper". If you cannot say that sentence about a comprehension you wrote, the comprehension is too complicated and you should turn it back into a loop. That test has never failed me in four years of club sessions.

One more piece of vocabulary before the exercises. A comprehension with square brackets gives you a list. The same thing with curly brackets and a colon gives you a dictionary. With curly brackets and no colon you get a set. The structure inside is identical, which is why learning the list version carries you most of the way to the other two.

Exercise One: Convert Loops You Have Already Written

Do not start with new problems. Start with code you already understand, because then the only new thing is the shape.

  1. Open any file from your earlier Python list practice and find a loop that builds a new list by appending.
  2. Copy the loop into a new file and leave it there, untouched, as your reference.
  3. Underneath it, write the comprehension version from memory. If you have to look back at the loop, that is fine; looking at a tutorial is not.
  4. Print both results and compare them with a simple equality check. They must match exactly, including order.
  5. Repeat with two more loops, then stop. Three conversions in one sitting is plenty.

Most people get the first one wrong by putting the for clause before the expression. The error message will mention invalid syntax and point at the for, which is a useful association to build early.

Exercise Two: Add a Condition at the End

Take a list of fourteen temperatures, some of them negative, and build a new list containing only the ones above freezing. The comprehension is temps_above = [t for t in temps if t > 0].

Now change the task. Build a list where cold readings are replaced by the string "frost" instead of being dropped. This forces you into a conditional expression at the front, which looks like [t if t > 0 else "frost" for t in temps], and the two positions of if are the single most confused point in this whole topic. The filtering if goes at the end. The choosing if goes at the start, and needs an else.

Write both, print both, and keep them side by side in the same file. When you need to remember which is which in six months, you will remember the file rather than the rule.

Exercise Three: Build a Dictionary From Two Lists

You have names = ["amara", "leo", "priya", "tomas"] and marks = [72, 65, 88, 54]. Produce a dictionary mapping each name to its mark, then a second dictionary containing only the students who passed with 60 or more.

The tool is zip, and the comprehension is {name: mark for name, mark in zip(names, marks)}. Add the filtering if at the end for the second version. Then try it with a marks list that is one item shorter than names, and notice that zip simply stops at the shorter one instead of raising an error. That silent truncation has eaten a real afternoon of my time on a club project, and knowing it exists is worth more than the exercise itself.

Exercise Four: The One That Should Stay a Loop

Here is where I part company with most tutorials. You will be told that comprehensions are more Pythonic and that rewriting loops as comprehensions is an improvement by default. That is true for the simple append pattern and false almost everywhere else.

The exercise: take a list of fifteen sentences and build a single list of every word longer than four letters, lowercased, with punctuation stripped. Write it as a nested comprehension, which will come out around 90 characters with two for clauses. Then write it as an ordinary loop with three or four short lines inside.

Now show both to someone who has been coding for about a month and ask which one they can explain. In my sessions the loop wins roughly nine times out of ten. Then time both with the timeit module on 50,000 sentences. On my laptop the comprehension came out at about 68 milliseconds and the loop at about 81, a difference of 13 milliseconds on a task you run once.

That trade is the whole lesson. You spent readability to buy 13 milliseconds. Sometimes that is correct, inside a tight inner function that runs a million times. Writing a club attendance script, it is not. The rule I teach is one for clause and at most one if; past that, use a loop and keep your evenings free. Debugging habits matter more than style points, which is the same argument as keeping your first functions doing one thing.

Exercise Five: Read, Do Not Write

The last exercise has no typing in it, and students resist it every term.

Find three comprehensions in code you did not write. A classmate's project, an open repository, a Stack Overflow answer. For each one, write out in plain English what it produces, then write out the equivalent loop by hand on paper, then run both and check you were right.

Being able to read these matters more than being able to write them. You will write a comprehension perhaps twice a week. You will read other people's several times a day once you work with anyone else, and a comprehension you cannot read is a bug you cannot find. If you want more in this direction, the python practice section has sets that build the same reading muscle on loops and conditions.

FAQ

Are list comprehensions faster than for loops?

Usually a little, because the append call is handled internally rather than looked up on every pass. On a list of 50,000 items the gap is typically 10 to 20 percent, which is invisible in a beginner program. Choose for clarity and treat speed as a bonus.

How long should a comprehension be?

If it does not fit on one line at a normal window width, it is too long. My working limit is one for clause, one optional if, and about 70 characters. Beyond that the loop is the honest version.

Can I use a comprehension without assigning the result?

You can, and you should not. Writing [print(x) for x in items] builds a whole list of None values just to get the printing side effect, then throws it away. Use a plain for loop when the point is the action rather than the new list.

What is the difference between a comprehension and a generator expression?

Round brackets instead of square ones give you a generator, which produces items one at a time instead of building the whole list in memory. For a few thousand items it makes no practical difference. For a file with two million lines it is the difference between working and running out of memory.

SD
Selene Dragomir

Selene coaches students for programming contests. She writes about practice problems, debugging and the habits that help beginners get unstuck on their own.

More posts by Selene

More in Python and Practice

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto