Given a list called animals containing the strings 'cat', 'dog', 'elephant', 'giraffe', fill in the first blank in the code to retrieve the first animal, the second blank to retrieve the last animal and the third blank to avoid an IndexError when accessing an element that is out of range. Note that an attempt is being made to access the eleventh element of the animals list, which doesn't exist. Instead, print 'List has less than 11 elements' when the list size is insufficient.
Accessing elements in a list and handling index errors
Report a typo
Fill in the gaps with the relevant elements
animals = ['cat', 'dog', 'elephant', 'giraffe']
first_animal = animals0]
last_animal = animals[-1]
out_of_index_animal = animals[10] if (animals) > 10 else "List has less than 11 elements"
print("First animal: " + first_animal)
print("Last animal: " + last_animal)
print("Out of index animal: " + out_of_index_animal)Create a free account to access the full topic
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.