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 trialTrace Harris
Python Web Development Techdegree Graduate 22,065 Pointstrying 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)
1 Answer
Alex Koumparos
Python Development Techdegree Student 36,887 PointsHi Trace,
For the approach you want to take, you should use type()
instead of isinstance()
. 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.
Cheers
Alex
Trace Harris
Python Web Development Techdegree Graduate 22,065 PointsTrace Harris
Python Web Development Techdegree Graduate 22,065 Pointsthat makes complete sense! that clears up a lot