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 Collections (2016, retired 2019) Lists Removing Items From A List

Don't understand what remove function actually does?

I the video an example of a list was used:

my_list = [1, 2 , 3, 1] my_list.remove(1)

Why does this not remove all numbers with the value of 1 immediately.... But just removes the first value of 1 in the list. I didn't really understand his explanation

1 Answer

Kyle Knapp
Kyle Knapp
21,526 Points

.remove() only removes the first item it finds in the list.

>>> arr = [1,2,3,1]
>>> arr.remove(1)
>>> arr
[2, 3, 1]

If you want to remove all 1's you can use filter.

>>> arr = [1,2,3,1]
>>> list(filter(lambda x: x != 1, arr))
>>> arr
[2, 3]

You could also use a while loop, but I don't recommend it.

>>> while 1 in arr:
      arr.remove(1)
>>> arr
[2, 3]

However the person does my_list.remove(1) again but this time it deleted the last item instead of deleting the second item.