If we think about it, the only time a new line can be added to the result set is if the parsed line is not empty.
Furthermore, we only have to check if we can add the current parsed line at the end of each input line.
Therefore, at each end of input line we just need to check if the parsed line is not empty and if we're not currently in a comment block.
We just have to iterate over each character of each line and modify the flag value to keep track of whether we're in a comment block, and then handle accordingly when we reach the end of each line.
def removeComments(self, source): result, parseLine, flag, fInd = , , False, -1 for line in source: for i,c in enumerate(line): if not flag: if c == '/' and i != len(line)-1 and line[i+1] in ('*', '/'): # comment start token if line[i+1] == '/': # if line comment, skip to end break flag, fInd = True, i+1 # activate flag and record position else: parseLine.append(c) # valid char elif c == '/': # potential block end prev = max(0, i-1) flag = (fInd == prev) or (line[prev] != '*') if not flag: # a parsed line can only be complete at the end of a line if parseLine: # only append if line isn't empty result.append(''.join(parseLine)) parseLine =  fInd = -1 # reset block comment start as the current line is done. return result