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 trial

Python

If we're defining a loop with def loopy(items): Why are we able to refer to 'items' as 'item', the non-plural version?

I don't understand the relationship between item and items. It seems to me we would have to refer to it as items throughout the rest of the code. Why are we able to take the S off? My code looks like:

def loopy(items): for item in items: if item == "STOP": break print(item)

I thought it should look like:

def loopy(items): for items in items: if items == "STOP": break print(items)

But this clearly doesn't work. What is 'item' and its relationship with 'items'?

1 Answer

Steven Parker
Steven Parker
243,656 Points

The names "item" and "items" are two different variables. The singular version is created by the loop:

    for item in items:

The first term is the "loop variable", which the loop creates for you. Then, on each pass, the loop assigns that to one of the elements of the iterable ("items"). You could use another name if you want, but since the iterable has a plural name, using the singular version of the name for the loop variable is a good choice to make the code easy to understand.

Perfect, thank you!