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 Python Sequences Sequence Iteration Iterating with Basic For Loops

Iterating with Basic For Loop

Hi,

I solved the challenge no problem, but am trying to wrap my head around the process and the code.

Using Ashley's example of printing her own name, the variable "letter" that we created new to print by character. However in the groceries example, the same statement (with a diff variable) prints out each item in quotes.

How does the compiler know that we wanted the items and not the characters within the quotes printed individually, or something else to that effect? Using my former C# brain, I could see if we assigned a print char or print string and how that would be different, but we don't do either in Python.

Thanks!

2 Answers

Hi Jordan,

A string in python is an iterable, so you could perceive it like a list.

So my_name = “Ashley” is in many ways the same as my_name = [“A”, “s”, “h”, “l”, “e”, “y”]

If you wanted to print the characters of each string element in the groceries list, you’d use a nested for loop like so...

app.py
for item in groceries:
    for letter in item:
        print(letter)

Hopefully that makes sense. Great question!

Hi Brandon, Awesome! This does help indeed. however just to be crystal clear, is letter a specific function that the interpreter recognizes? i don't see it being called, so i'm assuming it's a var that you just picked.. How does it exactly assign?

Sorry Jordan,

Letter is just a semantic variable. It gets assigned the value of each element in the list as the list is being iterated over.

You could just as easily write for barbecue in item:, and the results would be the same. I chose letter as the name of the variable because I know that variable will end up holding letters/chars.

So really quick review... On each iteration of the for loop, the variable declared after for (in this case, item and letter) is reassigned. And each time it is reassigned, it holds the next indexed value in the list.

Perfect.. thanks so much!