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

index error

whats wrong with the code?

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

1 Answer

andren
andren
28,558 Points

The thing you write in the brackets after "messy" is not the value you want to remove from the list but the index of the item you want removed.

In other words if you wanted to remove the first item from the list you would pass in 0, since list indexes start at 0 not at 1. If you wanted to delete the second item you would pass in 1, and so on.

So the thing that is wrong with your code is that you are asking Python to delete the 9th item of the list, since there are only 5 items you get an "out of range" error, since the value you provided is indeed higher than the actual number of items in the list.

Here is an example of how to use the del keyword with a list:

exampleList = [4, 6, 7, 9, 10, 53, 100]
# If I want to delete the 10 from the list I would write:
del exampleList[4]
# Since 10 is the fifth item which means it has an index of 4, since the index starts at 0.