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 trialGali B
2,082 Pointsmessy_list exercise problem
Hey folks. been working on the exercise asking me to filter out any non-int type item from 'messy_list'.
I wrote the code:
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
for item in messy_list:
if type(item) != int:
messy_list.remove(item)
whatever I didn't try, I couldn't get read of the second list (at index -1). eventually, I had to "cheat" and use del messy_list[-1] in order to pass the exercise...
How can I break that list into it separated objects and insert it into 'messy_list'?
3 Answers
Philip Schultz
11,437 PointsHey, You always want to make a copy of the list in this case. Don't use the same list in the for loop as the one you are trying to manipulate. Every time you are removing something from the list, everything shifts down one index, so items are being skipped.
loop_list = messy_list.copy()
for item in loop_list:
if type(item) is not int:
messy_list.remove(item)
Jay Maglione
646 PointsPhilip, thanks for this answer. I knew there was a more efficient way of writing this code to look for not type int. Great point about making a copy of the list as well!
Gali B
2,082 PointsThank you Philip. I understand my mistake now :)