Welcome to the Treehouse Community
Looking to learn something new?
Is there a way to check the data types in a loop ?
I can use del and remove the string and list and boolean one by one. But is there a way i could run the list through a loop and check the items for their data type????
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] # Your code goes below here X=messy_list.pop(3) messy_list.insert(0,X)
This is how I would do it:
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] # Your code goes below here messy_list.insert(0, messy_list.pop(messy_list.index(1))) copy_list = messy_list[:] # Make a copy of messy_list for item in copy_list: # Iterate over copy_list if type(item) is not int: del messy_list[messy_list.index(item)] # if the item isn't an int remove it from messy_list
You need to make a copy of messy_list because you can't remove items from a list while iterating over it.
If you've still got questions, don't hesitate to ask me :)
This is a functional way of solving this problem. It doesn't require explicit copy of the list and its just one line. Of course, don't give up readability for less code. I just wanted to show another way of doing it and if it makes sense for you, even better.
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] # filter will iterate through every element in messy_list, and you can access them with x. # If type(x) is int evaluates to True, then whatever element x is a the moment will be included # in the new list. clean_list = list(filter(lambda x: type(x) is int, messy_list)) print(clean_list)
This is a more functional programming style, if you have any questions, please let me know.