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
Stephen Link
3,685 PointsWhy do I need to loop twice to find all of the items I'm looking for?
I am working my way through the Learn Python course. I just completed the manipulating lists code challenge in the Lists Redux section. I was able to make it work but I don't understand why I had to take the approach that I took.
In this challenge you are presented with a list, the_list = ["a", 2, 3, 1, False, [1, 2, 3]], and then you have to use .remove() and/or del to remove all string, boolean, and list members from the_list.
In my initial approach I iterated over the list with a for loop and used isinstance() to test each item. I found that I could remove booleans and strings this way but I could not remove the list within the_list. This was really strange because some debugging that I did with print() showed that I was detecting the list within the_list.
After a lot of trial and error I created a second for loop which executes after the first one is complete. In this second for loop I once again used isinstance() to check for the list within the_list and this time I was able to remove the list within the_list.
So, I've passed the challenge but I don't see why I couldn't do this with one loop instead of two.
Here is the snippet of code that I tried initially. I don't understand why this does not work.
for item in the_list:
if isinstance(item, (str, bool, list)):
the_list.remove(item)
2 Answers
Juan Martin
14,335 PointsHello my friend.
I've checked your code, the returning list is the following:
[2, 3, 1, [1,2,3]]
I recommend you to not remove items on the same list you're iterating, always iterate on a copy of itself and inside the loop remove the items of the original list. Here's what I'm saying:
for item in list(the_list):
if isinstance(item, (str, bool, list)):
the_list.remove(item)
Using list(the_list) makes a copy of the original "the_list", with that you can assure that it will loop through the entire list.
Hope this works :)
Kenneth Love
Treehouse Guest TeacherYou, technically, don't have to use any loops for this :)
the_list.remove(False)
the_list.remove([1, 2, 3])
the_list.remove("a")