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 %
.
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!
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']
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