I've been given the assignment as follows:
Write a function called insert that takes 3 parameters, listA, listB and an index, then returns a copy of listA with the elements of listB inserted at the index. Your code should work with both strings and lists.
examples should look give this:
insert([1,2,3], ['a', 'b', 'c'], 3)
should give [1, 2, 'a', 'b', 'c', 3]
AND:
insert('dog', 'cat', 1)
should give 'dcatog'
I want to complete this first part both with and without loops. So far I have gotten:
def insert (listA, listB, index):
return listA[0:index] + listB + listA[index:len(listA)]
and this works out correctly, giving the correct example shown above. I don't know how to do this with loops, though. I've been trying to use for loops as follows:
def insert (listA, listB, index):
for nextchar in listA:
if nextchar == index:
listA.insert(index, listB)
return listA
but that's not correct. It's the closest I've gotten though, giving
[1, 2, ['a', 'b', 'c'], 3]
AND
'dog'
for the examples above.
but that's a nested list, yes? I don't want that. and the second example is completely wrong.