0
def new_insert(lst, i, e):
    lst = lst[:i] + [e] + lst[i:]
    
a = [0, 1, 2, 3, 4, 6, 7]
new_insert(a, 5, 5)
#Expected output: a = [0, 1, 2, 3, 4, 5, 6, 7]
    
b = ['0', '1', '0']
new_insert(b, 0, '1')
#Expected output: b = ['1', '0', '1', '0']

    
new_insert([1,2,3], 1, 0)
#Expected output = None

For the above code, I am unable to get the answer for the newly modified list when adding e into the list. When e = 0, the output should return None. How can I change the code, so that I can get my expected output?

kachiever
  • 7
  • 2

2 Answers2

0

Option 1:

You need to return the modified list from new_insert:

def new_insert(lst, i, e):
    return lst[:i] + [e] + lst[i:]

And then do:

a = [0, 1, 2, 3, 4, 6, 7]
a = new_insert(a, 5, 5)

Option 2:

Or just do:

def new_insert(lst, i, e):
    lst[:] = list[:i] + [e] + lst[i:]

if you don't want to return it from the function.

SpiderPig1297
  • 305
  • 1
  • 8
0

You need to return lst but also have an if condition and return none

def new_insert(lst, i, e):
    if (e == 0):
        return None

    lst = lst[:i] + [e] + lst[i:]

    return lst

a = [0, 1, 2, 3, 4, 6, 7]
print(new_insert(a, 5, 5))
#Expected output: a = [0, 1, 2, 3, 4, 5, 6, 7]

b = ['0', '1', '0']
print(new_insert(b, 0, '1'))
#Expected output: b = ['1', '0', '1', '0']


print(new_insert([1,2,3], 1, 0))
#Expected output = None


Hocli
  • 146
  • 3