-2

Possible Duplicate:
Remove all occurences of a value from a Python list

For a list:

char = ['a', '_', '_', 'b' ]

How does one remove all instances of '_' from the list, so it ends up looking like:

char = ['a', 'b' ] 

I've tried:

char.remove('_')

which gives me:

char = ['a', '_', 'b']

Why is this, and how can I get it to remove all underscores in the list?

Community
  • 1
  • 1
pearbear
  • 1,025
  • 4
  • 18
  • 23

2 Answers2

6

list.remove only removes the first instance of a match - you can use a list-comprehension:

char = [el for el in char if el != '_']
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

There are several options considered in this post that is a close duplicate perhaps of this one. One of them is :

>>> x = [1,2,3,2,2,2,3,4]  
>>> filter (lambda a: a != 2, x)  
[1, 3, 3, 4]
Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87