zeps
zeps

Reputation: 11

Inserting a string into a list only using the append method

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

Upvotes: 0

Views: 86

Answers (2)

han solo
han solo

Reputation: 6590

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']

Upvotes: 2

Aryerez
Aryerez

Reputation: 3495

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']

Upvotes: 2

Related Questions