Stuck at maintaning order


after i input my code i always has this problem and i cannot fix it. here is the error message :Oops, try again. Make sure to pass duck_index as the first argument in insert().

here is Instructions
Use the .index(item) function to find the index of "duck". Assign that result to a variable called duck_index.
Then .insert(index, item) the string "cobra" at that index.

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]

# Your code here!
duck_index = animals.index("duck")    # Use index() to find "duck"
print duck_index
animals.insert(2, "cobra")

print animals # Observe what prints after the insert operation


this line:

animals.insert(2, "cobra")

you use an index (a fixed one, 2) to insert. Instead, you should use the variable duck_index, this also contains the duck_index, but it makes your code more flexible.


thanks man it worked fine now


Why can't it be done using the number 2 there as well? Isn't that the actual index position of "duck"?


This does indeed work, but if you were looking to replace "duck" with :cobra" and you were to re-order the initial list, by hardcoding in 2, you will not do the proper replacement. But by just referencing the index of "duck" you can replace it with cobra regardless of where it is in the list.


@austink26 gives a perfect explanation why hardcoding something (using the number 2) can cause trouble.

So this lesson on purpose doesn't allow hardcoding


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