-3

So let's say I have a list as follows:

Li = ['1', '2', '3', '4', '5', '6', '7', '8']

I want to have a list modification to have this:

Li = ['12', '34', '56', '78']

Is it possible to merge every 2 elements of a list together?

pickle rick
  • 477
  • 2
  • 8

3 Answers3

1
>>> Li = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> [''.join(Li[i:i+2]) for i in range(0, len(Li), 2)]
['12', '34', '56', '78']
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

And if you prefer functional python:

list(map(lambda x: x[0]+x[1], zip(*[iter(Li)] * 2)))
Charalarg
  • 75
  • 1
  • 9
0

You could use map on striding subsets of the list that step by 2 and are offset by 1:

list(map(str.__add__,Li[::2],Li[1::2]+[""]))

['12', '34', '56', '78']

Note: The +[""] is there to cover cases where the list has an odd number of elements

Alain T.
  • 40,517
  • 4
  • 31
  • 51