Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

What is wrong in my code, but I can get my expected result.

I am trying to remove all "#" in the list.

funds_U is the list of data:

In [3]: funds_U
Out[3]: 
[u'#',
 u'#',
 u'MMFU_U',
 u'#',
 u'#',
 u'AAI_U',
 u'TGI_U',
 u'JAS_U',
 u'TAG_U',
 u'#',
 u'#',
 u'AAT_U',
 u'BGR_U',
 u'BNE_U',
 u'IGE_U',
 u'#',
 u'#',
 u'DGF_U',
 u'BHC_U',
 u'FCF_U',
 u'SHK_U',
 u'VCF_U',
 u'#',
 u'JEM_U',
 u'SBR_U',
 u'TEM_U',
 u'#',
 u'#',
 u'BAB_U',
 u'BGA_U',
 u'#']

The following is the code:

In [4]: for fund_U in funds_U[:]:
   ...:     funds_U.remove(u"#")
   ...:     

The following is the error:

ValueError                                Traceback (most recent call last)
<ipython-input-4-9aaa02e32e76> in <module>()
      1 for fund_U in funds_U[:]:
----> 2     funds_U.remove(u"#")
      3 

ValueError: list.remove(x): x not in list
like image 201
Terence Ng Avatar asked Dec 07 '22 07:12

Terence Ng


2 Answers

As per the documentation, if the item doesn't exist in the list, remove() will throw an error. Right now your code iterates through every item in the list and tries to remove that many #s. Since not every item is a #, remove() will throw an error as the list runs out of #s.

Try a list comprehension like this:

funds_U = [x for x in funds_U if x != u'#']

This will make a new list that consists of every element in funds_U that is not u'#'.

like image 200
thegrinner Avatar answered Dec 29 '22 12:12

thegrinner


I would do this so:

new = [item for item in funds_U if item!=u'#']

This is a list-comprehension. It goes through every item in funds_U and adds it to the new list if it's not u'#'.

like image 23
TobiMarg Avatar answered Dec 29 '22 12:12

TobiMarg