Learn
Python Lists and Dictionaries
Maintaining Order

Sometimes you need to search for an item in a list.

animals = ["ant", "bat", "cat"] print animals.index("bat")
  1. First, we create a list called animals with three strings.
  2. Then, we print the first index that contains the string "bat", which will print 1.

We can also insert items into a list.

animals.insert(1, "dog") print animals
  1. We insert "dog" at index 1, which moves everything down by 1.
  2. We print out ["ant", "dog", "bat", "cat"]

Instructions

1.

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.

Folder Icon

Take this course for free

Already have an account?