Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlexander Mazur
3,543 PointsSyntax question
for item in new_list: shopping_list.insert(spot, item.strip())
I am a bit confused about the for loop. Where is item defined? And how does it determine how the for loop will run?
2 Answers
Ryan Lail
4,386 PointsOkay, so in a for loop you will have:
for i in list:
The 'for' bit tells the program that this is a for loop. The 'i' bit is just a temporary variable (this means that it can be whatever you like. So you could have 'for item in list' for e.g. The 'in' part states that the data the loop needs to iterate over is coming next. The 'list' part is the name for the variable or list or whatever you want to iterate over. So if you wanted to iterate over a list called 'shopping_list', your for loop would read:
for item in shopping_list: #where I wrote 'item' you can write anything you like!
After that's set up you write what you actually want to to with each item. This may be print or find a certain index e.t.c.
So to conclude your final for loop syntax is:
for i in list:
#Do stuff (i.e. print)
MUZ140889 Dephine Chenayi Chihota
6,766 Pointsitem doesn't need to be defined. it is just a variable we are using to describe what is in our list. the syntax works just fine as it is. it is a way of telling the program that for whatever thing that is the list do something. if it were a list of numbers you could say for number in new_list, or even for num in new_list, this will work just the same and give the same answer.
Ryan Lail
4,386 PointsRyan Lail
4,386 PointsAlso the 'item' as you asked is defined in the first line in the loop. you don't need to define it beforehand. Also the loop will run until the data it's iterating over runs out (i.e. when the end of the shopping list is reached)