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
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'#'
.
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'#'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With