-5

I have a list

string = ['a', 'b', 'c', 'd', 'e', 'f']

I'm trying to make a space in between each 2 characters of the list so that it will become this:

['a', 'b', ' ', 'c', 'd', ' ', 'e', 'f']

I have tried this:

test = 0

while test != len(string):
    for i in range(2):

        string.append(' ')
    test = test + 1

print (string)

But it gives this error:

    Traceback (most recent call last):
  File "D:/Python/New folder (3)/test.py", line 8, in <module>
    string.append(' ')
MemoryError
3
  • 1
    Tutorial here. Commented Jun 6, 2015 at 23:50
  • 4
    Why so many down votes? This is a reasonable question. Commented Jun 7, 2015 at 0:15
  • 3
    It doesn't show research effort, and is unlikely to be useful to anyone who has done any research. Commented Jun 7, 2015 at 0:16

6 Answers 6

0

Use a list comprehension

Your test is never going to pass because you are appending to the list every time. You are actually appending to the end of the list so you will not get what you want like that.

An approach could be to use a list comprehension:

string = ['a', 'b', 'c', 'd', 'e', 'f']
#insert a space every two characters
new_string = [[s, " "] if i % 2 else s for i, s in enumerate(string)]
#flatten the list
new_string = [item for sublist in new_string for item in sublist]

This can be done in one line like so:

[item for sublist in [[s, " "] if i % 2 else s for i, s in enumerate(string)] for item in sublist]
Sign up to request clarification or add additional context in comments.

1 Comment

The == 1 part is unnecessary.
0

You could do it like this:

string = ['a', 'b', 'c', 'd', 'e', 'f']
newstring = []
i = 1

for x in string:
    if i > 2:
        newstring.append(' ')
        newstring.append(x)
        i = 1
    else:
        newstring.append(x)
    i += 1

print newstring

It seems much clearer to use this method and it returns the same result.

Comments

0

Since nobody actually explained your error properly:

Your while test != len(string): is never True as you keep appending to the original list so the list just keeps on growing and growing until eventually you run out of ram/memory, you should not iterate over and append to the same list, you would need to make a copy or just create a new empty list and append to that.

The list starts with 6 elements, you append 2 more before you test your condition again and increase test by 1 so after the first loop you now have 8 elements in your list and test is 1, next loop you have 10 and test is 2 and so on until you run out of memory...

There are better ways but if you were to use a loop and insert into the original list you would start at the third element and use a step of 3:

string = ['a', 'b', 'c', 'd', 'e', 'f']


for i in range(2, len(string)+2, 3):
        string.insert(i, " ")

print (string)

['a', 'b', ' ', 'c', 'd', ' ', 'e', 'f']

You can also use itertools.chain and catch the extra empty spaces at the end with ind < len(string) - 1:

from itertools import chain

print(list(chain.from_iterable((ele, " ") if ind % 2 and ind < len(string) - 1 else ele
                           for ind, ele in enumerate(string))))

['a', 'b', ' ', 'c', 'd', ' ', 'e', 'f'] 

Comments

0

Its not a compact solution, but its didatic:

a= ['1', '2','3','4','5','6']

Group 'a' in 2 characters:

for x in range(int(len(a)/2)):
    a[x]=a[x]+a.pop(x+1)

Then, a will become

['12', '34', '56']

Add a space to every item (except the last):

for x in range(int(len(a))-1):
    a[x]=a[x]+" "

Now lets make a new list splitting each of 'a' items:

b=[]
for x in range(int(len(a))):
    b.extend(list(a[x]))

The result:

['1', '2', ' ', '3', '4', ' ', '5', '6']

Comments

0

Given the list l of the characters, you could do the following :

l = ['a', 'b', 'c', 'd', 'e', 'f']

out = sum([l[2 * i:2 * (i + 1)] + [' '] for i in range((len(l) + 1) // 2)], [])[:-1]

The for loop runs through every other character and adds and empty space [' '] after every couple of characters found in the list l[2 * i:2 * (i + 1)].

The sum function can actually be called with a list, given that you provide it a start argument of the type list. See python sum function - `start` parameter explanation required.

Finally, the [:-1] part allows us to remove the last space.

Comments

-1

Use insert, not append. Append adds to the end.

string = ['a', 'b', 'c', 'd', 'e', 'f']
string.insert(4, ' ')
string.insert(2, ' ')

Or construct a completely new list that has the desired spaces.

out = []
for i, char in enumerate(string):
    out.append(char)
    if i != 0 and i % 2 != 0:
        out.append(' ')

The memory error is caused by your while loop never ending. Test grows by one per iteration, but the list grows by 2.

2 Comments

The list grows by 2 per iteration of the while loop.
You could replace if i != 0 and i % 2 == 0 with if i and i%2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.