简体   繁体   中英

How to remove Specific values in python list

result = [(u'ABC', u'(Choose field)', u'ABCD', u'aa', u'A', u'A_100')]

I'm trying to remove '(Choose field)' from the above list using the following syntax:

result.remove('(Choose field)')
# and  
result.remove("'(Choose field)'")

But both things are not working fine and it ends up with this error

{ValueError}list.remove(x): x not in list

First of all, your list contains tuple which contains string. And tuple doesn't support remove Just convert tuples as list and then use remove

>>> res = list(result[0])
['ABC', '(Choose field)', 'ABCD', 'aa', 'A', 'A_100']
>>> res.remove('(Choose field)')
['ABC', 'ABCD', 'aa', 'A', 'A_100']

You can convert the tuple inside the list to another list and remove the item from there. This should do the work:-

result = list(result[0])
result.remove(u'(Choose field)')

If you want to use indexing and specifically want to remove 'a' and 'b' from distinct list: values = ['a', 1, 2, 3, 'b'] - you can do this:

pop_list=['a','b']
[values.pop(values.index(p))  for p in pop_list if p in values]    

above will remove 'a' and 'b' in place - to get :

print(values)   

[1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM