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.remove()

Jan Lundeen
Jan Lundeen
5,885 Points

How do I delete items from a list without changing the list directly?

How do I delete items from states (the list name) without changing states directly? Here's the code:

states = [ 'ACTIVE', ['red', 'green', 'blue'], 'CANCELLED', 'FINISHED', 5,]

The question wants me to remove the last item from the list. Here's how I did it:

states.remove([5])

I couldn't include the comma after the 5 without getting a syntax error. The message I received is Don't change states directly.

Any ideas how to correct the list without changing the list (list is states).

Thanks!

lists.py
states = [
    'ACTIVE',
    ['red', 'green', 'blue'],
    'CANCELLED',
    'FINISHED',
    5,]

1 Answer

Ryan S
Ryan S
27,276 Points

Hi Jan,

Square brackets define a list, so when you are trying to pass in [5] into .remove(), you are trying to remove a list containing only one item, the number 5.

[5] does not exist in states, but 5 does.

When using .remove(), you need to provide only the item that you want to remove. You don't need to worry about commas because they are not part of the list items themselves (unless there is a list item that is a string that happens to have a comma in it).

states.remove(5)

There are other ways of accomplishing what the challenge is asking, such as using index values, but they will be shown in upcoming videos.

Good luck.

Jan Lundeen
Jan Lundeen
5,885 Points

Hi Ryan,

Thanks for your help! That worked. For some reason, I was thinking I need to put square brackets around anything I put in the parenthesis for the remove function (even if it's one item). It wasn't clear to me that square brackets are only used for the entire list. And regarding the comma, since it was not following anything, I thought I needed to correct that too. That's good to know about commas. I took off the square brackets around the 5 and removed the comma. That worked. Thanks!