0

I have encountered an error in attempting to clean data from a list.

This Code:

priceList = ['$301,000', '','3 days', '$33,333', '', '2 days', '$40,000', '6 days']

for i in priceList:
    if not "$" in i:
        priceList.remove(i)

Returns this output:

['$301,000', '3 days', '$33,333', '2 days', '$40,000']

Instead of this:

['$301,000', '$33,333', '$40,000']

Note the blank strings ( ' ' ) in the original list. Though these are removed as expected, the proceeding 'days' values are consequently skipped (the only days value ('6 Days') removed as expected does not have a preceding blank string.)

I have tried various methods to no avail.

braaterAfrikaaner
  • 1,072
  • 10
  • 20
bandit7
  • 1
  • 2
  • 4
    The problem is you are modifying a list while trying to iterate over it. After you delete items, the `for` loop pointer is wrong. Instead, build a new list that has the items you want to keep. – Tim Roberts Jan 04 '23 at 03:57

1 Answers1

1
>>> priceList = ['$301,000', '','3 days', '$33,333', '', '2 days', '$40,000', '6 days']
>>> priceList = [price for price in priceList if '$' in price]
>>> priceList
['$301,000', '$33,333', '$40,000']

or use filter by passing a lambda function to check if that symbol is present on elements

>>> list(filter(lambda x: '$' in x, priceList))
['$301,000', '$33,333', '$40,000']

# also is equivalent to define foo
def foo(x):
    return '$' in x
#...
>>> list(filter(foo, priceList))
['$301,000', '$33,333', '$40,000']
user11717481
  • 1
  • 9
  • 15
  • 25