4

how to remove elements from a list of strings while traversing through it. I have a list

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

i want to remove $ fro the list and if a ) or )% or % comes add that to the previous elemt of the list.
expected output is :

['', '32,324', '32', '(35)', '32,321']

what i have tried is

for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      list1[j-1] = list1[j-1] + element
      list1.pop(j)
   elif element == '$':
      list1.pop(j)

but the output i am getting is

['', '32,324', '32', '(35)', '$', '32,321']

whis is not the expected output. Please help

This question is different from the suggested reference is, here I have to do a concatenation with the previous element if the current element is ),)% or %.

Shijith
  • 4,602
  • 2
  • 20
  • 34

3 Answers3

3

Instead of attempting to remove and merge elements dynamically while iterating on the list, it will be much easier to make a new list based on the conditions here.

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

out = []
for element in list1:
    if element == "$":
        continue #skip if $ present
    elif element in ("%", ")", ")%"):
        out[-1] = out[-1] + element #merge with last element of out so far.
    else:
        out.append(element)

print(out)
#Output:
['', '32,324', '32', '(35)', '32,321']
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
3

What Green Cloak Guy said is mostly correct. Editing the size of the list (by calling .pop()) is causing you to have an unexpected j value. To me, the easiest way to fix this problem while keeping your existing code is to simply not mutate your list, and build up a new one instead:

new_list = []
for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      ret[len(ret) - 1] += element  # add at the end of the previous element
   elif element != '$':
      new_list.push(element)

However, I would encourage you to think about your edge cases here. What happens when a ')' is followed by another ')' in your list? This may be a special case in your if statement. Hope this helped!

Ryan Drew
  • 369
  • 2
  • 9
1

I think this list comprehension works (haven't seen an example of how % is handled):

[ (a+b if b in (')',')%','%') else a) for a,b in zip(list1,list1[1:]+['']) if a not in ('$',')',')%','%')]

The idea is to:

  • make a list of pairings of elements and their successors
  • filter out elements that should be removed
  • add the successor as appropriate to those that we keep
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101