Python Python Sequences Sequence Iteration Iterating with Basic For Loops

Jordan young
PLUS
Jordan young
Courses Plus Student 5,250 Points

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

Brandon White
seal-mask
MOD
.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...

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

Hopefully that makes sense. Great question!

Jordan young
Jordan young
Courses Plus Student 5,250 Points

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