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 trialwan muhammad najmie wan sabri
1,943 PointsWhy is this line of code marked incorrect?
Why is this line of code doesn't work?
list.index(8) should return the index position of the number 8 right?
or is it because nesting is not allowed in python?
messy = [5, 2, 8, 1, 3]
del messy[messy.index(8)]
2 Answers
Eray Ates
14,292 PointsI think its about test cases. Let's assume you don't know result of messy.index(8) but you will pass this question think like that.
The code work well on python interpreter.
dublinruncommutr
5,944 PointsNesting is allowed - but as Eray points out - if you don't know what is in the list and you call del with a nested call to index of a non-existent value, you'll get a ValueError:
>>> messy = [5,2,8,1,3]
>>> del messy[messy.index(10)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 10 is not in list
>>>
It would be safer to do something like this where you check if the value is in the list before calling index:
if 8 in messy:
del messy[messy.index(8)]
Then you can be certain you're not going to throw any ValueErrors for calling index on a value that doesn't exist in your list.
wan muhammad najmie wan sabri
1,943 Pointsi see. thank you! your suggestion makes sense and more organized to me
wan muhammad najmie wan sabri
1,943 Pointswan muhammad najmie wan sabri
1,943 Pointsi see. thank you for your clarification! it really helps a newbie like me