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 merge every three (or more) elements of list in one in python?

list = [1, 'one', 'first', 2, 'two', 'second', 3, 'three', 'third', 4, 'four', 'fourth', 5, 'five', 'fifth', 6, 'six', 'sixth']

is it compact way to make new list like this? (merging 3 elements, then another 3…):

['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fivefifth', '6sixsixth']

>Solution :

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

Using a list comprehension with conversion to string and join:

N = 3
out = [''.join(map(str, lst[i:i+N])) for i in range(0, len(lst), N)]

Output:

['1onefirst',
 '2twosecond',
 '3threethird',
 '4fourfourth',
 '5fivefifth',
 '6sixsixth']
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