-2

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

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

items2 = ['e4ee', '4548', ... 
  • Possible duplicate of [How do I split a list into equally-sized chunks?](https://stackoverflow.com/questions/312443/how-do-i-split-a-list-into-equally-sized-chunks) with an added string join – Sayse Aug 18 '22 at 07:24
  • 1
    Why don't you want to create a new list and then just assign its reference to *items* – DarkKnight Aug 18 '22 at 07:27

2 Answers2

2

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']
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • This is exactly what I wanted. Maybe I just worded incorrectly but what this is what I mean by not creating a new list. – UnknownDrilla Aug 18 '22 at 07:31
-1

If you absolutely do not want to create a new list (as stated):

result_len = len(items) // 4
for i in range(result_len):
    j = (i*4)
    items[i] = ''.join(items[j:(j+4)])
for i in range(len(items) - 1, result_len - 1, -1):
    del items[i]

Does exactly len(items) iterations and never creates a new list.

The first loop updates the first result_len items in the list to the desired values. The second one deletes the rest of the items from it.

EDIT: Whoops, had a bug there. Now it should be correct.

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41