Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to join two words together in a list with a space in the middle?

I have a list like this :

['which', 'means', 'which', 'one','which', 'will]

How can I possibly join two words together and form this:

['which means', 'which one', 'which will']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here’s an option using join and zip:

>>> words = ['which', 'means', 'which', 'one', 'which', 'will']
>>> [' '.join(z) for z in zip(words[::2], words[1::2])]
['which means', 'which one', 'which will']

Breaking it down a little to show what the slice operation [::2] does and what zip does:

>>> words[::2], words[1::2]
(['which', 'which', 'which'], ['means', 'one', 'will'])
>>> list(zip(words[::2], words[1::2]))
[('which', 'means'), ('which', 'one'), ('which', 'will')]

A neat thing about this method is that you can change the number of words in the grouping very easily by using another iteration to build the arguments to zip:

>>> list(zip(*(words[i::3] for i in range(3))))
[('which', 'means', 'which'), ('one', 'which', 'will')]
>>> [' '.join(z) for z in zip(*(words[i::3] for i in range(3)))]
['which means which', 'one which will']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading