Home > Software engineering >  Is there a way to make list insert & list pop in def function?
Is there a way to make list insert & list pop in def function?

Time:10-27

I want to make a def function that have same effect with list insert and list pop.

First, List insert have no return value. I make a def list_insert.

def list_insert(lst, index, obj, /):

lst = [1, 2, 3]
lst_insert(lst, 1, 6)

Second, List pop have return value. I make a def list_pop.

def list_pop(lst, index=-1, /):
    
lst = [1, 2, 3]
list_pop(lst, 1)

But I don't know how to unravel these method in def function.

CodePudding user response:

You could use slice assignment:

def list_insert(lst, index, obj, /):
    lst[index:index] = [obj]

lst = [1, 2, 3]
list_insert(lst, 1, 6)
lst
# [1, 6, 2, 3]

def list_pop(lst, index=-1, /):
    if 0 <= index < len(lst):
        lst[:] = lst[:index]   lst[index 1:]
    else:
        raise IndexError

lst = [1, 2, 3]
list_pop(lst, 1)
lst
# [1, 3]

CodePudding user response:

first of all, i don't get it why do you want to make function instead of using list.insert() or list.pop(). but anyway here is my code:

    def list_insert(lst,index,obj):
        lst.insert(index,obj)
        print(lst)

    def list_pop(lst,index=-1):
        lst.pop(index)
        print(lst)

    list1 = [1,2,3,4]
    list_pop(list1,2) #or list.insert(list1,1,1.5) for example

if this doesn't help you please explain more & be more specific about what you want.

  • Related