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

Python Enumerate and Zip Practice With Five Exercises

A student at our Tuesday club spent eleven minutes last month hunting a bug in four lines of code. She had a list of twelve student names and a list of twelve marks, and she wanted to print each name with its mark and a position number.

A laptop screen showing a short Python loop using enumerate and zip beside a notebook of worked exercises

A student at our Tuesday club spent eleven minutes last month hunting a bug in four lines of code. She had a list of twelve student names and a list of twelve marks, and she wanted to print each name with its mark and a position number. Her loop ran over range(len(names)), printed positions starting at zero, and crashed on the last iteration because she had written marks[i + 1] while trying to fix the zero. Every piece of that bug came from managing an index by hand.

Two built in functions remove almost all of that work, and most beginners meet them weeks later than they should. I teach them in the same session now, because the pair of them turns index arithmetic into something you read rather than something you calculate. The exercises below are the ones I use, and they are ordered so that each one breaks a specific habit.

What the two functions actually hand you

Enumerate wraps any iterable and yields pairs: a counter and the item. Written out, for position, name in enumerate(names) gives you both without a single subscript. The counter starts at zero unless you pass a second argument, so enumerate(names, 1) gives you human numbering straight away, which is the fix my student needed and never found.

Zip takes two or more iterables and yields tuples made of one item from each, stopping when the shortest one runs out. So for name, mark in zip(names, marks) walks both lists in step. Combine them and you get for position, (name, mark) in enumerate(zip(names, marks), 1), which looks dense the first time and reads cleanly by the third.

Both return lazy iterators rather than lists. That is the detail that trips people up later, and it is worth proving to yourself early: assign pairs = zip(a, b), loop over it once, then loop again and watch the second loop do nothing at all. The iterator is exhausted. Wrap it in list() if you need it twice.

Five exercises, in this order

Do these with a text file and a terminal rather than a notebook, and type them out instead of copying. Each one should take five to fifteen minutes. If you get stuck for longer than that, the approach in our note on getting unstuck without peeking is more useful than a solution.

  1. Numbered shopping list. Given items = ["rice", "lentils", "oil", "salt"], print each one as 1. rice through 4. salt. Use enumerate with a start of 1 and no arithmetic anywhere in the loop body. Then change the start to 10 and check that your output runs from 10 to 13 without touching anything else.
  2. Name and mark table. With names = ["Ana", "Bilal", "Chen"] and marks = [88, 71, 95], print one line per student showing name and mark aligned in columns. Use zip. Then add a fourth name to the names list only, run it again, and write down what happened to your output before you read the next section.
  3. Find the positions of a value. Given temps = [19, 23, 23, 18, 23], build a list of every index where the value equals 23, so the answer is [1, 2, 4]. Solve it with enumerate and a condition. Then solve it again as a list comprehension on one line, and keep both versions in the file so you can compare them next week.
  4. Differences between neighbours. Given a list of daily step counts, print how much each day changed from the day before. The clean solution uses zip(steps, steps[1:]), which pairs each item with the one after it. Work out on paper why the slice shifts the second sequence by one and why the result is one item shorter than the input.
  5. Two files, line by line. Write two small text files, questions and answers, with the same number of lines. Open both and loop with zip to print each question followed by its answer, numbered with enumerate. Then delete the last line of the answers file and run it again. Your program will not complain, and understanding why is the point of the exercise.

Exercise five is the one I care most about. A loop that silently processes four of your five records is harder to notice than a crash, and in a contest it costs you the whole problem.

The mistakes I see every term

Silent truncation is first and worst. Zip stops at the shortest input, so mismatched lengths produce a shorter result rather than an error. In Python 3.10 and later, zip(a, b, strict=True) raises a ValueError when the lengths differ, and I now ask students to write strict every time unless they have a reason not to. On older versions, assert the lengths match on the line before the loop.

Second is forgetting that zip and enumerate are consumed once. A student builds pairs = zip(names, marks), uses it to print a report, then tries to use the same variable to compute an average and gets zero. No error, just a wrong answer, which is the kind of bug that teaches real debugging habits.

Third is unpacking in the wrong shape. Looping over enumerate(zip(a, b)) yields an index and a tuple, so for i, name, mark in ... fails with a message about unpacking. The parentheses in for i, (name, mark) in ... are doing real work, and reading that error message carefully is faster than guessing, which is also the message of our piece on reading a Python error message.

Fourth is dictionaries. Looping over a dict with zip gives you keys, not values, because iterating a dict yields keys. Use d.items() when you want both, and note that it already gives you pairs, so wrapping it in zip achieves nothing.

When a plain range loop is still the right answer

The advice you will hear most often is that range(len(x)) is a beginner smell and enumerate is always better. I say that myself about four times a term and it is still only mostly true. There are three cases where I write the range loop on purpose and would not mark a student down for it.

The first is when you need to assign back into the list. for i in range(len(scores)): scores[i] = scores[i] * 2 is honest about what it does. Enumerate gives you a copy of the value, so assigning to the loop variable changes nothing, and students who have not understood that spend an hour wondering why their list is unchanged.

The second is index arithmetic that reaches in both directions. If the logic needs i minus one and i plus two, writing the index yourself is clearer than building three shifted sequences, even if a comprehension would be shorter.

The third is when the index is the data. Looping over grid coordinates, or over a fixed number of rounds in a game where nothing is stored in a list, is what range is for. Reaching for enumerate there means inventing a list to count.

What I would retire entirely is the hybrid: for i in range(len(names)): name = names[i]. That line is enumerate written the long way, with an extra chance to mistype an index. If you find one in your own code, rewrite it before you do anything else. More drills of this shape sit in our Python and practice section.

FAQ

Can enumerate start at a number other than zero?

Yes, pass it as the second argument. The start affects only the counter it yields, never which items you get, so numbering a list from 1 costs you nothing and removes the plus one from your print statement.

What happens if I zip lists of different lengths?

You get a result as long as the shortest input and no warning at all. Pass strict equals True on Python 3.10 and later to turn that into an error, or check the lengths yourself first.

Can I zip more than two lists?

Any number. zip(names, marks, grades) yields three item tuples, and the same shortest input rule applies across all of them. Unpack with as many names as you passed iterables.

How do I undo a zip?

The star operator does it: given a list of pairs, zip(*pairs) gives you back two sequences. It is a neat trick for contest work and worth practising once, after you are comfortable with the exercises above.

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