Python for Absolute Beginners Transcripts
Chapter: Organizing and reusing code with functions
Lecture: Concept: for-in loops

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's review this idea of for in loops.
0:03 The for in loop is excellent for
0:05 going through a collection of items.
0:07 This is extremely common in programming.
0:10 In programming you'll be given a bunch of stuff
0:12 and you're like, well, I have to go through
0:13 each one individually and do something with it.
0:15 Maybe the user typed it in.
0:16 Maybe it's a file, you want to go through every line.
0:19 Maybe it's something you got off the internet.
0:21 You call some API and it sends you back a bunch of data.
0:24 Who knows what it is?
0:25 But you go through them always the same way.
0:27 So here we have plays, which is a collection
0:30 a sequence with three items: rock, paper and scissors.
0:33 We want to go through each one
0:35 and show them to the user.
0:37 Here we're going to actually print them
0:38 on the same line, so there's this cool trick
0:40 we can do with print and we can say end
0:42 instead of being a new line
0:44 a line break, it can be a space.
0:46 For each time we do a print statement
0:48 it just piles up on the end as a space.
0:50 You could put comma
0:51 you could put a dash, whatever you want.
0:53 So we're going to say for p in plays.
0:56 We're going to print that out.
0:58 Rock and then paper and then scissors.
0:59 That's pretty cool.
1:01 But a lot of times we need to actually know the number.
1:03 Like, we're asking the user, enter one, two, or three
1:06 and then that will correspond to rock, paper or scissors.
1:10 So if we want to do that, we go and have the same for in loop
1:13 but we use the enumerate keyword
1:15 and we can control the start position.
1:17 Talking to humans, usually start equals one.
1:20 If you just need to know the index in the list
1:22 then leave it alone, you'll get zero, one, two, three.
1:25 And then we have two elements that come out
1:27 into our loop there, so we say four idx comma p
1:30 so index and the play is going to come out
1:34 and then we can work with them both at the same time.
1:37 You'll see these loops everywhere.
1:38 They're super, super common.
1:40 They're the other type of loop that you have
1:42 in Python other than the while loop.
1:44 While loops are great for I want to do a condition
1:46 as long as something is true
1:48 but for in loops are super powerful
1:50 because they let you take a collection of things
1:52 and work with them, each one of them individually.