0

I'm struggling with a question at the moment and was wondering if someone could point out and show me where I'm going wrong. I need to insert a string into a list only using the append method at a designated position specified by an insert_position. Here is my code:

str1_list = ['one', 'three', 'four']

def insert_value(my_list, value, insert_position):

       new_list = []
       for i in range(len(my_list)):
             if i < insert_position:
                 new_list.append(my_list[i])
             elif i == insert_position:
                 new_list.append(my_list[i])
             else:
                 new_list.append(my_list[i-1])

       return new_list

print(str1_list, 'two', 1)

Output should be:

['one', 'two', 'three', 'four']

I know the value parameter needs to be somewhere but can't figure out where. Any help will be greatly appreciated.

Thanks

3
  • 2
    Have you tried stepping through the code manually? Also, consider: how many times do you expect the loop to run, and how many times does .append need to be called on new_list? Commented Nov 11, 2019 at 10:29
  • Your code doesn't call "insert_value". Commented Nov 11, 2019 at 10:31
  • Do you really need to use the .append method ? Anything else is accepted ? no methods in view at all ? Commented Nov 11, 2019 at 10:45

2 Answers 2

2

You have a few errors (not using the value passed to the function, not caling the function, unneccesary condition). Compare you code with this:

str1_list = ['one', 'three', 'four']
def insert_value(my_list, value, insert_position):
    new_list = []
    for i in range(len(my_list)):
        if i == insert_position:
            new_list.append(value)
        new_list.append(my_list[i])
    return new_list
print(insert_value(str1_list, 'two', 1))

Output:

['one', 'two', 'three', 'four']
Sign up to request clarification or add additional context in comments.

1 Comment

I see where I have gone wrong. I needed to first append the value and then insert it at the index of i. Thanks
2

You could just add the new value with the slice like,

>>> def insert_value(l, value, pos):
...     l[pos:pos] = [value]
...     return l # return is not required, since you want to modify the list ?
... 
>>> l = ['one', 'three', 'four']
>>> insert_value(l, 'two', 1)
['one', 'two', 'three', 'four']
>>> l
['one', 'two', 'three', 'four']

Comments

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.