why i getting IndexError: list index out of range

Question:

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 (‘_’).

Examples:

  • ‘abc’ => [‘ab’, ‘c_’]
  • ‘abcdef’ => [‘ab’, ‘cd’, ‘ef’]

https://prnt.sc/E2sdtceLtkmF



# **My Code:**

def solution(s):
    ```n = 2
    ```sp = [s[index : index + n] for index in range(0, len(s), n)]
    
    ```if len(sp[-1]) == 1:
        sp[-1] = sp[-1] + "_"
        ```return sp
    ```else:
        ```return sp
    
        

and i geting this error:

Traceback (most recent call last):
  File "/workspace/default/tests.py", line 13, in <module>
    test.assert_equals(solution(inp), exp)
  File "/workspace/default/solution.py", line 5, in solution
    if len(sp[-1]) == 1:
IndexError: list index out of range

# pls someone help

Asked By: Giorgi Maisuradze

||

Answers:

its fixed by adding another if condition which checking sp is empty or not

def solution(s):
    n = 2
    sp = [s[index : index + n] for index in range(0, len(s), n)]

    if len(sp) == 0:
       return sp

    if len(sp[-1]) == 1:
       sp[-1] = sp[-1] + "_"
       return sp

    else:
       return sp
Answered By: Giorgi Maisuradze

You need to test for the possibility that the input parameter is an empty string.

def solution(s):
    n = 2
    sp = [s[index : index + n] for index in range(0, len(s), n)]
    if sp and len(sp[-1]) == 1:
        sp[-1] += '_'
    return sp
Answered By: Cobra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.