Rakesh
Rakesh

Reputation: 103

How to merge the elements in a list sequentially in python

I have a list [ 'a' , 'b' , 'c' , 'd']. How do I get the list which joins two letters sequentially i.e the ouptut should be [ 'ab', 'bc' , 'cd'] in python easily instead of manually looping and joining

Upvotes: 3

Views: 170

Answers (2)

Neeraj Komuravalli
Neeraj Komuravalli

Reputation: 306

Just one line of code is enough :

a = ['a','b','c','d']
output = [a[i] + a[i+1] for i in xrange(len(a)) if i < len(a)-1]
print output

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

Use zip within a list comprehension:

In [13]: ["".join(seq) for seq in zip(lst, lst[1:])]
Out[13]: ['ab', 'bc', 'cd']

Or since you just want to concatenate two character you can also use add operator, by using itertools.starmap in order to apply the add function on character pairs:

In [14]: from itertools import starmap

In [15]: list(starmap(add, zip(lst, lst[1:])))
Out[15]: ['ab', 'bc', 'cd']

Upvotes: 4

Related Questions