Trace HarrisPython Web Development Techdegree Student 19,216 Points
trying to loop through an list and remove items that are not a number
So in this exercise I am trying to compare each item in messy_list to whether it is an integer or not I am trying isinstance(<var>,int) to execute my comparisons. Then if the statement is falsey I am using the .remove method remove the non integer I understand that I can remove use the .remove method three, separate times however I am trying this method for dry purposes. it seems more elegant. Error I am getting is Bummer looks like you have more items to remove from the "list". so I feel like I am on the right track just missing a piece.
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 isinstance(item, int) is False: messy_list.remove(item)
Alex KoumparosPython Web Development Techdegree Student 35,893 Points
For the approach you want to take, you should use
type() instead of
isinstance() returns True if the tested object is of the specified type or is a subclass of the specified type. Bool is a subclass of int so when you check isinstance() for ints, that False element in the array is going to be treated as an int. The
type() function, in contrast, returns the exact type of the tested object. So you can write something like:
type(x) == type(7)
And you will only get back True if x's type is the same as 7's type (which, of course is int).
Hope that clears everything up for you.