Gali Berkowiz1,444 Points
messy_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]]
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'?
P S10,184 Points
Hey, 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)
Philip, 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!