261,590 views
40 votes
40 votes
Python PleaseDefine a recursive function named insert, that expects an index, an item, and a Lisp-like list as arguments. The function returns a list in which the item is inserted at the given index position.Here is an example of its use:>>> lyst = buildRange(1, 5)>>> lyst(1 2 3 4 5)>>> insert(2, 66, lyst) # insert 66 at position 2(1 2 66 3 4 5)>>> lyst(1 2 3 4 5)

User Vesii
by
3.1k points

1 Answer

14 votes
14 votes

Answer:

Step-by-step explanation:

def insert(index, item, lyst):

if index == 0:

return [item] + lyst

if len(lyst) == 1:

return lyst[:index] + [item] + lyst[index:]

else:

return lyst[:index] + [item] + insert(0, lyst[index])

User Tuomas Laakkonen
by
3.1k points