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.
travis ueki2,102 Points
Can't figure out the data type of lists in order to result in my for loop removing the nested list
In the last elif I want to check the condition of (psuedo code)
for item in list: elif item == list: the_list.remove(item)
the_list = ["a", 2, 3, 1, False, [1, 2, 3]] # Your code goes below here the_list = ["a", 2, 3, 1, False, [1, 2, 3]] # Your code goes below here newItem = the_list.pop(3) the_list.insert(0, newItem) def cleanUp(list): for item in list: if item == 'a': list.remove('a') print(list) continue elif item == False: list.remove(item) print(the_list) continue elif item == type(list): list.remove(item) print(list) continue cleanUp(the_list)
Chris FreemanTreehouse Moderator 68,064 Points
The statement you are looking for is
isinstance(item, list) to check if item is of type
list. There are two issues with this approach.
You are using the key word
listas your argument name for
cleanUpwhich overwrites the namespace and
listis no longer the
typebut instead has the value of the argument passed to
cleanUp. It is not a good idea to use
listor any keyword as a variable name. Is is common to you "lst" for a list variable.
You are operating on the same list you are looping over. What happens is the list is shortened by the
removeactions then the loop thinks it's done since the length is less and doesn't loop over the last item.
also, since all the code covered by an
continue statements aren't needed:
newItem = the_list.pop(3) the_list.insert(0, newItem) def cleanUp(mylist): for idx, item in enumerate(mylist[:]): if item == 'a': mylist.remove('a') elif item == False: mylist.remove(item) elif isinstance(item, list): mylist.remove(list(item)) cleanUp(the_list)
The last item can also be removed using
the_list.pop() which removes the last item in the list:
the_list.remove('a') the_list.remove(False) the_list.pop()