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

Iterating with Basic For Loop


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.


2 Answers

Brandon White
.a{fill-rule:evenodd;}techdegree seal-36
Brandon White
Treehouse Moderator

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

for item in groceries:
    for letter in item:

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?

Brandon White
.a{fill-rule:evenodd;}techdegree seal-36
Brandon White
Treehouse Moderator

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!