Home > Software design >  Merging every 2 elements of a list in Python
Merging every 2 elements of a list in Python

Time:09-17

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?

CodePudding user response:

>>> 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']

CodePudding user response:

Try this:

[Li[i] Li[i 1] for i in range(0,len(Li),2)]

Or:

[a b for (a,b) in (zip(Li[::2],Li[1::2]))]

CodePudding user response:

And if you prefer functional python:

list(map(lambda x: x[0] x[1], zip(*[iter(Li)] * 2)))

CodePudding user response:

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

  • Related