Search code examples
pythontokencombinations

How to get all concatenation of list elements in order in Python?


background

I have lists of numbers and symbols like:

[1,':',2022,'.','01','.','01']

I would like to call a function like is_date(string) on every concatenation of the elements in order.


minimal example

Considering the simple example [1,2,3] as input, the expected list of concatenations should be: ['1','12','2','123','23','3']

I would like not to get '13' in the results

So afterwards I could call:

for token in list_of_concatenation:
    if is_date(token):
        do something

Solution

  • You can use a double loop, slicing, and string concatenation:

    l = [1, 2, 3]
    l2 = [str(x) for x in l]
    [''.join(l2[i:j+1]) for i in range(len(l2)) for j in range(i, len(l2))]
    

    output: ['1', '12', '123', '2', '23', '3']