Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Lists Redux Shopping List Take Three

Alexander Mazur
Alexander Mazur
3,543 Points

Syntax 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

Okay, 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)

Also 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)

item 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.