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

Merge every certain number of items in a list

I have a list like this

items= ['e', '4', 'e', 'e', '4', '5', '4', '8', 'a', '8', '6', 'd', '8', 'a', 'e', '1', 'b', '6', '2', '1', '6', 'a', 'a', 'a', '2', 'b', 'd', '6', '7', '7', '9', '2']

I want to edit the list so that every 4 items in the list get merged like this

items=['e4ee', '4548', 'a86d', '8ae1', 'b621', '6aaa', '2bd6', '7792']

Edit: My mistake for wording. By not creating a new list I meant by putting the arranged elements into a separate list like this

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

items = ['e', '4', 'e', 'e', ...

items2 = ['e4ee', '4548', ... 

>Solution :

You could do it like this although this does create a new list:

items = ['e', '4', 'e', 'e', '4', '5', '4', '8', 'a', '8', '6', 'd', '8', 'a', 'e', '1', 'b', '6', '2', '1', '6', 'a', 'a', 'a', '2', 'b', 'd', '6', '7', '7', '9', '2']

items = [''.join(items[i:i+4]) for i in range(0, len(items), 4)]

print(items)

Output:

['e4ee', '4548', 'a86d', '8ae1', 'b621', '6aaa', '2bd6', '7792']
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