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 For Loops

Devan Laton
Devan Laton
602 Points

I need help with this for loop

I'm not sure how to do this properly, any help

iterating_lists.py
rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
    for color in rainbow:

1 Answer

Angelus Miculek
Angelus Miculek
6,293 Points

Hey Devon!

When looping over a list, a for loop executes code as many times as there are items in the list.

"color" is just a variable (you can name it anything) that points to each item in the list corresponding to what repetition it's on -- that's the cool thing. Example:

refrigerator = ['broccoli', 'kale', 'cabbage', 'spinach', 'avocado', 'onion']
for healthy_veg in refrigerator:
    print(healthy_veg)

This will output:

broccoli
kale
cabbage
spinach
avocado
onion

This loop will iterate 6 times because there are 6 items in the list.

first iteration: the variable healthy_veg points to 'broccoli'

second iteration: healthy_veg points to 'kale'

third iteration: healthy_veg points to 'cabbage'

fourth iteration: healthy_veg points to 'spinach'

fifth iteration: healthy_veg points to 'avocado'

sixth iteration: healthy_veg points to 'onion'


A while ago, I also had trouble understanding this. I hope I made it clear for you, now.

If you need any more help, just say the word!