Search code examples
pythonliststring-concatenation

Conditional joining in a list


I have a Python list:

data = ['Cost', '$', 4244, '$', 4090, '$', 3967]

What I want to do is merge the $ with preceding element and obtain a new list:

data = ['Cost', '$4244', '$4090', '$3967']

What is the best way to achieve this?


Solution

  • You could make use of iterators:

    data_iter = iter(data)
    [e + str(next(data_iter)) if e == '$' else e for e in data_iter]
    

    This makes use of the fact we can obtain the next element of an iterable, even while looping over the iterable. Each time a '$' string is found, the next element is pulled in and concatenated as a string.

    Demo:

    >>> data = ['Cost', '$', 4244, '$', 4090, '$', 3967]
    >>> data_iter = iter(data)
    >>> [e + str(next(data_iter)) if e == '$' else e for e in data_iter]
    ['Cost', '$4244', '$4090', '$3967']