Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm stuck with an list exit error in python

I am a beginner python programmer and I started doing exercises in codewars and Ive got the following assignment:

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').

solution('abc') # should return ['ab', 'c_'] solution('abcdef') # should return ['ab', 'cd', 'ef']

now I wrote the following code which gives me the correct result:

def solution(s):
    l = [s[i:i+2] for i in range(0,len(s) ,2)]
    if len(l[-1]) == 1:
        l[-1] += "_"
    return l

print(solution('abc')) -> ['ab', 'c_']
print(solution('asdfadsf')) -> ['as', 'df', 'ad', 'sf']

but when I send submit my code to code wars I get the following error:

if len(l[-1]) == 1: IndexError: list index out of range

an error which I don't get if I test in visual studio code.

can someone please explain to me how can I fix this? thanks !! :)

like image 671
Michael Ben Haym Avatar asked Nov 19 '25 10:11

Michael Ben Haym


1 Answers

The problem is l[-1] for an input of ''. In that case your list comprehension returns an empty list [] that has no l[-1] element.

Check empty string input seperately:

def solution(s): 
    if not s: 
        return []

    l = [s[i:i+2] for i in range(0,len(s) ,2)]
    if len(l[-1]) == 1:
        l[-1] += "_"
    return l

print(solution('abc')) # -> ['ab', 'c_']
print(solution('asdfadsf')) # -> ['as', 'df', 'ad', 'sf']

print(solution('')) # -> [] 
like image 194
Patrick Artner Avatar answered Nov 22 '25 00:11

Patrick Artner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!