Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a str.join() for lists?

Tags:

python

list

I understand str.join():

>>> '|'.join(['1','2','3'])
'1|2|3'

Is there something which outputs a list? Is there a function that will output:

['1', '|', '2','|', '3']

That is, a str.join() for lists? (or any other iterable?)

like image 325
poundifdef Avatar asked Feb 18 '23 15:02

poundifdef


2 Answers

list('|'.join(['1','2','3']))

should do the trick where you are working with a list of chars.

A more generic solution, that works for all objects is:

from itertools import izip_longest, chain

def intersperse(myiter, value):
    return list(
        chain.from_iterable(izip_longest(myiter, [], fillvalue=value))
    )[:-1]

I'm not aware of a built-in/std-library version of this function.

In action:

print intersperse([1,2,3], '|')

outputs:

[1, '|', 2, '|', 3]
like image 147
Adam Wagner Avatar answered Mar 06 '23 07:03

Adam Wagner


How about this?

>>> list('|'.join(['1','2','3']))
['1', '|', '2', '|', '3']
like image 22
jterrace Avatar answered Mar 06 '23 08:03

jterrace