0

I do the "for x in y" loop in python, and try to delete every empty ("") element. But it doesn't catch every empty element, and I have to run it multiple times.

I tried changing the output and manually loading it into an array, which didn't work either. I tried it on Python3.4 aswell, but the same problem persisted there.

temp  
Output: ['18:10:01', '', '', '', '', '', '', '', 'all', '', '', '', '', '', '0.42', '', '', '', '', '', '0.00', '', '', '', '', '', '0.48', '', '', '', '', '', '0.03', '', '', '', '', '', '0.18', '', '', '', '', '98.89']  

for c in temp:  
     if(c==''):  
             temp.remove(c)  


temp  
Output: ['18:10:01', 'all', '0.42', '0.00', '', '0.48', '', '', '', '', '', '0.03', '', '', '', '', '', '0.18', '', '', '', '', '98.89'] 

I expected it to go through the array and delete every empty element, leaving only the data i want. But as you can see from the output of the last line, it isn't the case. It still has quite a few empty elements.

Chris
  • 75
  • 6

2 Answers2

1

Your problem is most likely that you're modifying your list as you iterate through it, which can get all manner of confusing.

The best way to solve your problem is using List Comprehension like so:

temp = [li for li in temp if li != '']

This will create a new list out of only list items that aren't blank strings.

I would recommend looking more into list comprehension, as it is a powerful tool.

Ahndwoo
  • 1,025
  • 4
  • 16
0

You are trying to remove element from an array that is being iterated. It is messing up the indices internally. A better way would be to return a new array with no empty string.

result = [item for item in the_list if item]
MjZac
  • 3,476
  • 1
  • 17
  • 28