Reputation: 653
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.
Upvotes: 0
Views: 184
Reputation: 320
For the "dog" example, remember that strings in Python are immutable... that is, they can't be changed. So if you are trying to insert some characters into a string "dog", it won't be changed.
Strings don't have the "insert" method at all, so you will get an error in the "dog" example.
You will need to create a new string, and NOT use the insert method, if it's a string being passed in.
Upvotes: 1
Reputation: 63
Your example is a bit off I believe.
insert([1,2,3], ['a', 'b', 'c'], 3)
should in fact return
[1, 2, 3, 'a', 'b', 'c']
Anyhow, here's my fix:
def insert (listA, listB, index):
if index == len(listA):
listA.extend(listB)
return listA
for i in range(len(listA)):
print i
if i == index:
for j, b_elem in enumerate(listB):
listA.insert(i+j, b_elem)
return listA
A bug with your given code is that you are inserting a list into that index of listA, as opposed to inserting each element of listB STARTING from that index.
Upvotes: 0