#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 2: loop counting == enumerate

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Next up, counting inside a loop. So sometimes you want to keep track of an index when you loop over a sequence,
0:08 and when you come from C or another language you would typically do something like this. Let's define a list of days
0:17 and let's loop through them showing the day prepended by the number. Alright, so that's straightforward. Now, and this is correct, right?
0:32 I mean you can do it like this, it's all 100% correct. But the more idiomatic or Pythonic way is to use enumerate.
0:41 And a way to do it is to wrap your sequence in enumerate, which returns the index and the item in the sequence on every loop. So I can just, now,
0:54 print those, and it should give me, oops, obviously, I should not hard code days. So I'm using f-strings by the way because I'm on Python 3.6.
1:07 And yes, this gives me the same result, and there's even a nice little trick with enumerate, which is, you can give it a starting point.
1:15 So I can just copy this, and again give enumerate a second argument of 1. So I want to start the counter at 1, and then I don't have to do this menu
1:26 plus 1 inside the loop. And that gives me the same result.

Talk Python's Mastodon Michael Kennedy's Mastodon