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


#1

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.


FAQ: Learn Python: Python Lists and Dictionaries - Maintaining Order