0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jeremy
  • 613
  • 1
  • 6
  • 7
  • Please remember to tag your questions with the language. – Barmar Oct 18 '13 at 22:45
  • Your examples are not consistent. In the first example you're counting indexes from 1, but in the second example you count from 0. Which is it? – Barmar Oct 18 '13 at 22:47
  • In your loop, instead of inserting `listB` at the index, you need to use a second loop to insert each element of `listB` separately. – Barmar Oct 18 '13 at 22:49
  • Also, make sure you have the indentation correct in your loop. That's critical in python. – Barmar Oct 18 '13 at 22:50
  • possible duplicate of [Python - append vs. extend](http://stackoverflow.com/questions/252703/python-append-vs-extend) – msw Oct 18 '13 at 22:59

2 Answers2

1

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.

Grizz
  • 320
  • 1
  • 11
0

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.

beeftaco
  • 63
  • 5