John John - 1 year ago 130
Python Question

Joining elements of a list - Python

I'm fairly new to python (a couple of weeks) and have run into a problem joining a list. Now, I know that a list can be joined to make one long string as in:

x = ['a', 'b', 'c', 'd']
print ''.join(x)

Obviously this would output:


However, what I am trying to do is simply join the fist and second strings in the list, then join the third and fourth and so on. In short, from the above example instead achieve an output of:

['ab', 'cd']

Is there any simple way to do this? I should probably also mention that the lengths of the strings in the list will be unpredictable, as will the number within the list, though the number of strings will always be even. So the original list could just as well be:

['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r']

or whatever.
Anyways, any help at all would be greatly appreciated so thanks in advance. :)

Answer Source

You can use slice notation with steps:

>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
>>> x[1::2] #1. 3. 5 ..
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.