0

I have a variable:

x = 4

And I have a list:

list = [{'name': u'A', 'value': '1'}, {'name': u'B', 'value': '4'}, {'name': u'C', 'value': '2'}]

How can I exclude/remove the element in list where value=x?

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
maksymov
  • 493
  • 9
  • 22
  • possible duplicate of [Remove all occurences of a value from a Python list](http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list) – Marcin Feb 18 '12 at 15:37
  • this isn't an exact duplicate, because it is a property of the value, not the value itself. – Donald Miner Feb 18 '12 at 16:00

1 Answers1

8

A list comprehension is perfect for this.

[ k for k in list if int(k['value']) != x ]

You can also use filter, but I believe list comprehensions are preferred in terms of style:

filter(lambda p: int(p['value']) != x, list)

edit: noticed your values are strings, so I added an int conversion.

Donald Miner
  • 38,889
  • 8
  • 95
  • 118
  • 3
    [List comprehensions are indeed preferred over `map()` and `filter()` (and don't even think about `reduce()`!)](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) The BDFL says so! – Li-aung Yip Feb 18 '12 at 15:49