How to use the insert method correctly for Python

Viewed 409

I'm having trouble with this question:

Write a function insert_item_end(data, item) that takes a list data, and item as a parameter and returns a new list that contains item at the end of the data using the insert method (i.e. you cannot use append).

This is what I've done so far:

data.insert(-1, item)

However, this only returns None.

Here is an example of what I want to return:

([1, 2, 3, 4, 5], 1) returns [1, 2, 3, 4, 5, 1]

3 Answers

Do this suit your requirement?

def insert_item_end(data,item):
    newlist=[];
    newlist=data
    newlist.insert(len(data),item)
    print(newlist)


data=[1, 2, 3, 4, 5];
item=1

insert_item_end(data, item)

you can use

data.insert(len(data),item)

technically -1 and len(data)-1 should also work but i don't know why its inserting at the second last position.

You can simplify @Priyankarao's function by simply modifying the list that's passed to your function, instead of defining a new one. Something like this:

def append_to_list(data,item):
    data.insert(len(data),item)
    return data

Then run it like so:

nums = [1, 2, 3, 4, 5];
item = 6

newlist = append_to_list(nums, item)
print(newlist)

Output:

[1, 2, 3, 4, 5, 6]
Related