Python Jumpstart by Building 10 Apps Transcripts
Chapter: App 4: Journal app and file I/O
Lecture: Core concept: For-in loops

Login or purchase this course to watch this video and the rest of the course contents.
0:00 We just saw the for-in loop in action. And this is one of our core concepts from this application, let's take a moment and dig into it more deeply.
0:10 Now for-in loops are the easiest and the safest way to process any collection. It doesn't have to be just lists,
0:17 anything that is a collection can be used in one of these for-in loops. So here we have an items list
0:23 it has three strings in it, 'cat', 'hat' and 'mat', and we can go through those and print them out in order just saying for item in items:
0:32 we can call item that variable anything we want as long as it doesn't conflict with the existing other variables
0:38 and we just make that up on the spot as part of the loop and then we could use it within the loop
0:43 so we say for item in items print() and then we just work with the item. Now, that is what you will write most of the time,
0:49 but sometimes you want a number, an index, a position associated with that item. And when that is the case,
0:56 you wrap your collection in a call to enumerate and you get back both an index, and an item, and you can work with those.
1:02 You can either grab it as a tuple or as I am doing in this particular example I am projecting or unpacking that tuple,
1:10 into the two variables idx for index and item for the actual item.


Talk Python's Mastodon Michael Kennedy's Mastodon