TAGS :Viewed: 4 - Published at: a few seconds ago

[ Pop from empty list error ONLY on lists with even number of elements ]

So this is just an exercise I'm doing for fun on codewars.com. The point is to take a string and pull it apart by taking the last character and adding it to a string, taking the first character and adding it to another string until you have either 1 (for a string with an odd number of letters) or 0 (for a string with even number of letters) characters left. Here's a link to the challenge if you're interested.

def pop_shift(test):
    firstSol = []
    secondSol = []
    testList = list(test)
    while len(testList) != 1:
        firstSol.append(testList.pop())
        secondSol.append(testList.pop(0))
    return [''.join(firstSol), ''.join(secondSol), ''.join(testList)]

My code gives me the right result if the string has an odd number of characters:

['erehtse', 'example', 't']

But with an even number of characters I get this error:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    pop_shift("egrets")
  File "<pyshell#35>", line 6, in pop_shift
    firstSol.append(testList.pop())
IndexError: pop from empty list

I've looked through a bunch of questions involving the pop() method, but nothing sounded quite similar to this. I've also tested this with a variety of strings and looked into the documentation for the pop method. There must be something that I'm missing. Any pointers are appreciated. This is also my first question, so if there's anything else you'd like to see, please let me know.

Answer 1


Your loop is checking to see if the length of the list isn't 1; for an even length list, since you always pop 2 items at a time, it will never see a length of 1.

Answer 2


Instead of while len(testList) != 1, you need: while len(testList) > 1, since len(testList) will jump from 2 to 0 on "even" strings:

def pop_shift(test):
    firstSol = []
    secondSol = []
    testList = list(test)
    while len(testList) > 1:
        firstSol.append(testList.pop())
        secondSol.append(testList.pop(0))

    return [''.join(firstSol), ''.join(secondSol), ''.join(testList)]

Then:

print(pop_shift("Monkeys"))
> ['sye', 'Mon', 'k']

print(pop_shift("Monkey"))
> ['yek', 'Mon', '']