Maintaining Order - Error with list indexing


#1



https://www.codecademy.com/courses/python-beginner-en-pwmb1/1/4?curriculum_id=4f89dab3d788890003000096#


The error message I'm getting is "Oops, try again. Make sure to pass duck_index as the first argument in insert(). "


The whole point of this exercise was to insert "cobra" at the index position of "duck" (which is 2). The window prints out the new list with cobra in the correct position so the code is functional. Why would I pass duck_index into my .inster()?


animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
print duck_index# Use index() to find "duck"

# Your code here!
animals.insert(2, "cobra")


print animals


#2

The interpreter already gives a clue that you should pass duck_index as the first argument on the insert method. This is the right thing to do for this exercise, rather than use 2.

Recall that this line

is already performing the index position you are targeting, but in a more dynamic way. Sometimes, you might have a long array and instead of looking for the position, you look for the object itself, in this case, animal itself.

I hope this helps.


#3

That worked perfectly! Thank you! I was honestly confused because it was printing out exactly what I wanted...


#4

You're welcome.Glad I could help.

Have fun coding! :slight_smile:


#5

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
print duck_index# Use index() to find "duck"

Your code here!

animals.insert(duck_index, "cobra")

print animals


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.