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 trialMary McCarthy
1,805 Pointshaving trouble cleaning up messy list
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
Your code goes below here
messy_list.insert(0,messy_list.pop(3))
for item in messy_list:
if type(item) == bool: messy_list.remove(item) else: try: item = int(item) except TypeError: messy_list.remove(item) except ValueError: messy_list.remove(item) else: continue
print(messy_list)
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
# Your code goes below here
messy_list.insert(0, messy_list.pop(3))
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
# Your code goes below here
messy_list.insert(0,messy_list.pop(3))
for item in messy_list:
if type(item) == bool:
messy_list.remove(item)
else:
try:
item = int(item)
except TypeError:
messy_list.remove(item)
except ValueError:
messy_list.remove(item)
else:
continue
print(messy_list)
2 Answers
Kip Yin
4,847 PointsIt would be a lot easier without using remove()
:
int_list = []
for item in messy_list:
if type(item) == int:
int_list.append(item)
messy_list = int_list
Despite the efficiency, this is kinda cheating. If you need to use remove()
, you need to be careful ** not to iterate and remove items from a list at the same time. ** To avoid this, you can store all unwanted values in a separate list, and then iterate through this list to remove items:
trash = []
for item in messy_list:
if type(item) != int:
trash.append(item)
for item in trash:
messy_list.remove(item)
But still, I think using a filter is the fastest way of doing this:
messy_list = list(filter(lambda x: x if type(x) == int else None, messy_list))
Mary McCarthy
1,805 PointsThanks that is helpful!