Why doesn’t it accept my duck index when I try to insert?

Question

Why doesn’t it accept my duck index when I try to insert?

Answer

While it may be true that the value ultimately stored in our variable duck_index is 2, that doesn’t mean we should hardcode a 2 as our insertion index.
What if we inserted stuff, deleted some other stuff, and then wanted to insert the cobra at the duck’s current index? Would it still be 2? Possibly! But to have a program that works regardless of the duck’s position, we want to use the variable we created solely for that purpose: duck_index.
If we wanted to do something similar for the "emu", we might do this:

emu_index = animals.index("emu")  # Find the index of our emu

animals.insert(emu_index, "earwig")  # Make use of the emu_index here

Rather than (3, "earwig"), because that’d be hardcoding a value, which we want to avoid in general.

12 Likes

notice, too, that the duck_index variable definition was already started on line 2.
That got me; I didn’t see it and tried to define the variable myself from scratch.

8 Likes

I don’t get whats wrong

animals = [“aardvark”, “badger”, “duck”, “emu”, “fennec fox”] # Use index() to find “duck”
animals.insert(2, “cobra”)

Your code here!

duck_index = animals.index(“duck”)

print animals # Observe what prints after the insert operation

I’m afraid I can’t test this lesson at the moment but I think the process goes like-

  1. get the duck_index
  2. use this index to insert "cobra"
  3. print

So you’d want to collect your duck_index before the call to .insert() and I’d hazard a guess that instead of hard-coding the index you would want to use the duck_index name like so lst.insert(duck_index, 'string').

function “append” is used to append a new word into an existing list
BUT
i won’t be able to index my new word (i can’t give my new word a specific position in the list)
while
function “insert” can be used to append and as well index my new word

if that is correct?
are there other differences between “append” and “insert”?
if I’m wrong please correct me.

The only important bit I’d add on is that append sticks an element on the end of the list which is an important distinction. You could always get the index with the length of the updated list (-1 to account for zero indexing).

You’ve got the idea behind .insert though. If you don’t need to insert an element in a specific place in a list then append is almost always the right choice.

For small lists I wouldn’t worry about it but inserting into a list can be a very expensive operation as Python’s lists are implemented as dynamic arrays (contiguous memory and therefore insertion may require copies and moves). Worth keeping in mind in case you are ever working with large lists (or numerous insert operations).

1 Like