Reputation: 452
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
Upvotes: 5
Views: 19025
Reputation: 12241
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'#'
.
Upvotes: 9
Reputation: 251051
This will modify the original object, so in case there were other variables pointing to the same object then their links will remain intact.
FUNDS_U[:] = [x for x in FUNDS_U if x != "#"]
Upvotes: 1
Reputation: 3807
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'#'
.
Upvotes: 6