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

Karrar Al Arbo
Karrar Al Arbo
842 Points

lists - sublists

why is my code wrong ?

musical_groups = [
    ["Ad Rock", "MCA", "Mike D."],
    ["John Lennon", "Paul McCartney", "Ringo Starr", "George Harrison"],
    ["Salt", "Peppa", "Spinderella"],
    ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Scott Shriner"],
    ["Chuck D.", "Flavor Flav", "Professor Griff", "Khari Winn", "DJ Lord"],
    ["Axl Rose", "Slash", "Duff McKagan", "Steven Adler"],
    ["Run", "DMC", "Jam Master Jay"],]


newlist=[]

def enlisting(list):

    number_of_lists = len(list)    # length of the main list
    n=0
    for sublist in (list [:]):          # it shall print the main list number of times equal to sublists 
        if n != number_of_lists :
            n +=1 
            for a in (sublist [:]) :
                newlist.append(a)
    print(", ".join(newlist))            

enlisting(musical_groups)
Steven Parker
Steven Parker
244,139 Points

It's not clear what the objective is, or what course and lesson you are referring to. You might want to take a look at this video about Posting a Question. And for when your question refers to something you are doing in a workspace, you may also want to view this one about sharing a snapshot of your workspace.

1 Answer

Steven Parker
Steven Parker
244,139 Points

I managed to find the Multidimensional Musical Groups challenge in the Introducing Lists course. After testing your code, I discovered that the function does not have access to the global variable "newlist".

You can fix that either by moving the variable declaration inside the function (recommended), or by giving the function access to it by declaring global newlist at the start of the function. It's also not necessary to have a function at all, the challenge can be met with just inline code (which would also resolve the access issue).

And FYI, while it doesn't keep it from working, the code is unnecessarily complex. You don't need the slices or extra parentheses in the loops. For example: "for a in (sublist [:]) :" can just be "for a in sublist:".