#100DaysOfCode in Python Transcripts
Chapter: Appendix: Python language concepts
Lecture: Concept: for-in
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
In Python we have a fantastically simple way to work with collections and sequences. It's called the "for...in" loop and it looks like this.
0:09
You just say for some variable name in some collection, so here we have "for item in items" and that creates the variable called item
0:17
and we are looping over the collection items, it just goes through them one at a time, so here it will go through this loop three times,
0:23
first time it will print the item is "cat", the second time it will print the item is "hat" and then finally the item is "mat".
0:30
And then it will just keep going, it will break out the loop and continue on. Some languages have numerical "for" loops, or things like that,
0:35
in Python there is no numerical "for" loop, there is only these for in loops working with iterables and sequences.
0:42
Because you don't have to worry about indexes and checking links and possible off-by-one errors, you know,
0:47
is it less than or less than or equal to, it goes in the test in the normal "for" loop. This is a very safe and natural way to process a collection.
0:55
Now, there may be times when you actually need the number, if you want to say the first item is "cat", the second item is "hat",
1:00
the third item is "mat", this makes it a little bit challenging. Technically, you could do it by creating an outside variable, and incrementing,
1:07
but that would not be the proper Pythonic way. The Pythonic way is to use this enumerate function, which takes a collection
1:14
and converts it into a sequence of tuples where the first element in the tuple is this idx value, that's the index, the number.
1:22
And the second item is the same value that you had above. So first time through its index is zero, item is cat;
1:28
second time through, index is one, item is hat, and so on. So these are the two primary ways to loop over collections in Python.
1:36
Remember, if you need to get the index back, don't sneak some variable in there, just use enumerate.