One of the two versions of my code has been rejected

one of the two versions of my code has been rejected in this exercise

Version 1 is ok. But, version 2 works the same, but it was rejected ( the feedback is: “Function insert did not return the expected value”). What is the reason ?

list_1 = ["A", "B", "C", "E"]


# Version 1
def insert(list_x, object_x, index_x):
    return list_x[:index_x] + [object_x] + list_x[index_x:]


print(insert(list_1, "D", 3))

# Version 2

def insert(list_x, object_x, index_x):
    list_x.insert(index_x, object_x)
    return list_1
print(insert(list_1, "D", 3))

I have one additional question to this exercise:
How can I place the argument in the definition that the value ( in this example: the value of the index) can only be positive? is there any way to do so? Or the only way is to put it inside the definition for ex:

def insert(list_x, object_x, index_x):

    if index_x < 0:
        return False

Im thinking about something like that ( pseudocode):

def insert(list_x, object_x, index_x >= 0):

Hello @drill_n_bass

I suppose you meant to return list_x and not list_1.


Moreover, the exercise assumes that it will feed only non-negative indexes for answer checking purposes.
Ideally, as you pointed out, index_x should be checked for proper bounds.
If you still want to have that check, you should do it before calling the function or inside the function as the requirement desires.
For this exercise, that check isn’t required.

1 Like

could someone tell how to do such “positive” bound ?

Hi @drill_n_bass,

Actually, the way that you came up with at the beginning looks good enough: just to check first inside the function if index_x is negative:

def insert(list_x, object_x, index_x):
    if index_x < 0:
        return False
    else:
        ...

Why don’t you want to use it? :slightly_smiling_face:

thank you for confirmation of good approach !

1 Like