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 trial

Python Python Basics (2015) Python Data Types List cleanup

wan muhammad najmie wan sabri
wan muhammad najmie wan sabri
1,943 Points

Why 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?

lists.py
messy = [5, 2, 8, 1, 3]
del messy[messy.index(8)]

2 Answers

Eray Ates
Eray Ates
14,292 Points

I 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.

wan muhammad najmie wan sabri
wan muhammad najmie wan sabri
1,943 Points

i see. thank you for your clarification! it really helps a newbie like me

dublinruncommutr
dublinruncommutr
5,944 Points

Nesting 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
wan muhammad najmie wan sabri
1,943 Points

i see. thank you! your suggestion makes sense and more organized to me