Search code examples
python-3.xlistconcatenation

Remove and concat elements from a list while iterating


I'm working with python and I have the following list:

mylist = ['Module(stmt* body, type_ignore *type_ignores)', '| Interactive(stmt* body)', 'FunctionDef(identifier name, arguments args,','stmt* body, expr* decorator_list, expr? returns,','string? type_comment)']

I want to concat one element of the list with the previous one if the second element do not end by ) and the previous element don't begin with |, then remove the second element. For instance, mylist should be transformed as:

mylist = ['Module(stmt* body, type_ignore *type_ignores)', '| Interactive(stmt* body)', 'FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)']

I have written the following recursive code:

def test(line1, line2):
    if line1[-1] != ')' and line2[0] != '|':
       return True, line1 + line2
else:
    return False, line1


def concat_rule(lines):
    for index in range(len(lines)):
        if index + 1 >= len(lines):
            return lines
        value = test(lines[index], lines[index + 1])
        if value[0]:
            lines[index] = value[1]
            del lines[index + 1]
            break
    if value[0]:
        return concat_rule(lines)

It works but I wonder if it exists a simplest solution with comprehensive list.


Solution

  • No need for recursion - you can use a simple loop. (I'm not sure if a list comprehension can help here.)

    Here is a version that does in-place modification:

    index = 1
    while index < len(mylist):
        if mylist[index - 1][-1] != ')' and mylist[index][0] != '|':
            mylist[index - 1] += mylist.pop(index)
        else:
            index += 1
    

    and here is a version that makes a new list:

    output = [mylist[0]]
    for item in mylist[1:]:
        if output[-1][-1] != ')' and item[0] != '|':
            output[-1] += item
        else:
            output.append(item)