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

Removing list items by number in Python

Hey everyone,

I have a question about lists; so say for instance I had a list of items, and I wanted the user to be able to view an enumerated list of the items and then remove an item by selecting the corresponding number. I know we can enumerate a list like so:

names = ['spam', 'eggs', 'killer rabbit' , 'coconuts']

for id,name in enumerate(names,1):
    print(str(id) + '.',name)

But suppose I wanted to allow the user to select '1' to remove the first item. I was thinking I could somehow assign a value to each index and remove items based on that, but I'm not sure how to approach that. As always, any help is appreciated, thanks again!

1 Answer

Steven Parker
Steven Parker
243,318 Points

Since index numbers start at 0, the index number could be computed as the selected item number minus one.

Then, you can simply delete that item from the list: "del names[index]".