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 Introducing Lists Build an Application Wrap Up

Tibor Ruzinyi
Tibor Ruzinyi
17,968 Points

Please explain me how the loop is itterating thru items

Can please somebody explain me how is this loop working

for group in musical_groups:
    if len(group) == 3:
        print((", ").join(group))

I passed the challenge , but iam a bit confused. Does the for loop go thru the whole multidimensional list in the first row ?Where are the items stored till we start to working with them , in this case we are checking the length? In the ram memory ?

UPDATE just got to the second task and now I understand.

Can someone also weigh in on why we're only running through and .join() -ing the groups with 3 members? The prompt says to run through all groups and join them.

1 Answer

Nice work on completing the challenge

The for loop allows you to iterate through each object in a list one by one and it's fine (although a bit confusing sometimes) if that object happens to be another list like we have in the challenge. As with all for loops, the variable name after the keyword 'for' represents the object at that index, so at first iteration, group = musical_groups[0]. 2nd iteration, group = musical_groups[1] etc. Hopefully this answers your question about where the items are assigned.

Does the for loop run through each object in the first dimension (ie the group)? Yes, but only one by one

Does the for loop run through each object in the second dimension (ie. the group members)? In this instance, no, the for loop here is allowing us a means of accessing it but doesn't loop through it. The reason you're able to print the items in the 2nd dimension list is with the ", ".join() method. We are essentially using this method to directly access the information in the list and printing it

# Iteration 1
for group in musical_groups: # group = musical_groups[0]
    if len(group) == 3: # is length of 'group' compared to 3? True!
        print((", ").join(group)) # print items in 'group' joined with ", "

# Iteration 2
for group in musical_groups: # group = musical_groups[1]
    if len(group) == 3: # is length of 'group' compared to 3? False! There are not 3 items in this list
        print((", ").join(group)) # doesn't print

# and so on...