Python Python Basics (2015) Python Data Types Lists

Dave Masom
Dave Masom
9,584 Points

Remove all instances of a value from a list

Is there a way to remove all instances of a value in a list? For example, if I have: my_list = [1, 2, 3, 3, 3]

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

Can I call a method to remove all of the 3s in my_list?

Hi Dave, glad to help. It took me a few minutes to figure it out and when I got it I was pleasantly surprised.

Seth, it looks like yours is creating a new list out of only the desired characters? Kinda like the opposite of what I did?

2 Answers

This seemed to work. Though I'm sure there are more graceful ways to do it. I'll be curious what someone else will suggest.

for num in my_list:
    my_list.remove(3)
Seth Kroger
Seth Kroger
Treehouse Moderator 56,273 Points
my_list = [x for x in my_list if x != 3]

works too

Dave Masom
Dave Masom
9,584 Points

Thanks John, it worked for me too. And I understood your solution as well - even better!

I tried both methods and Seth's ended with the results intended and John's left me with a syntax error! not sure what I did wrong?

my_list = [54321, 3, 3, 3]
my_list
[54321, 3, 3, 3]
for num in my_list: my_list.remove(3)
... my_list
File "<stdin>", line 2
my_list
^
SyntaxError: invalid syntax

I didn't get a syntax error, but it left one 3 when running the code on you're list. Seths code is cooler anyway :D Ok, I ran my code in the python shell and got that syntax error, but it did remove all the 3's. So I would have to add some more code to clean it up. Seths is still better.

What does x for x in my_list mean? I didn't understand your solution.

Seth Kroger
Seth Kroger
Treehouse Moderator 56,273 Points

It's called a list comprehension. Comprehensions are kinda unique to Python (it is the only major language to have them). It's a bit like a for loop but it basically means "make a new list but running through the items of the old list and checking if they meet a condition". You can check out this workshop for more: https://teamtreehouse.com/library/python-comprehensions