# Join vectors strings on Python

In R I can join together a vector of strings using paste:

> a = 1:3 > a [1] 1 2 3 > b = 4:6 > b [1] 4 5 6 > d = 7:9 > d [1] 7 8 9 > together = paste(a, b, d, sep='-') > together [1] "1-4-7" "2-5-8" "3-6-9"

How can i do the same in Python ?

## Answers

Vectorized operations in R can be approximated in Python by list comprehensions or the built-in function map().

Here, we use zip to do parallel iteration over the three lists.

a = range(1,4) b = range(4,7) c = range(7,10) together = ['-'.join(str(i) for i in z) for z in zip(a,b,c)]

Output:

>>> together ['1-4-7', '2-5-8', '3-6-9']

One subtlety in the above code is that the argument to join is a generator expression which means it's evaluated lazily. To be even lazier, replace zip with izip from the itertools package.

How about your own function:

def f(*args): return '-'.join([str(a) for a in args])

and then map

map(f, a, b, c) # ['1-4-7', '2-5-8', '3-6-9']

Or for fun (and any number of values):

map(lambda *args: '-'.join(map(str, args), a, b, c)

adding a one-liner assuming 3 element lists

l1 = range(1,4) l2 = range(4,7) l3 = range(7,10) map(lambda x,y,z: '%s-%s-%s' % (x,y,z), l1, l2,l3)

a = range(1,4) b = range(4,7) c = range(7,10) together = ['{}-{}-{}'.format(*x) for x in zip(a, b, c)]

EDIT:

zip(a,b,c) iterates over (a[0], b[0], c[0]), (a[1], b[1], c[1]), etc. Instead of using ['{}-{}-{}'.format(x, y, z) for x, y, z in zip(a, b, c)], we can use * argument unpacking as above.