Back

List methods - Answers

 Q1. Get the following code working in Python:

animals = ['cow','goat','dog','rat']

print('There are', len(animals), 'animals in this list:')
for item in animals:
print (' ',item)

print('\n')

animals.append('cat')
animals.insert(1,'eagle')
animals.remove('rat')
animals.index('dog')
animals.append('dog')
animals.count('dog')

print('There are', len(animals), 'animals in this list:')
for item in animals:
print (' ',item)

print('\n')
print('Dog appears',animals.count('dog'),'times.')
print('\n')

animals.sort()
print('There are', len(animals), 'animals in this list:')
for item in animals:
print (' ',item)

print('\n')

Q2. To add a zebra to the end of the list: animals.append('zebra')


Q3. To add another zebra to the list so it is the third item along (remember, index = 2): animals.insert(2,'zebra')
Q4. To count the number of zebras in the list and display an appropriate message: print('There are now', animals.count('zebra'), 'zebras in the list')
Q5. To display a message that states what position 'eagle' is at: print('Eagle is at position',animals.index('eagle'))
Q6. To print out the list in alphabetical order:

animals.sort()
print('\n')
print('There are now', len(animals), 'animals in this list, in alphabetical order:')
for item in animals:
print (' ',item)

Q7. To print out the list in reverse alphabetical order, sort them first, then:

animals.reverse()
print('\n')
print('There are now', len(animals), 'animals in this list in reverse alphabetical order: ')
for item in animals:
print (' ',item)

Q8. To remove all the items from the list so it is an empty list:

print('\n')
animals.clear()
print('There are', len(animals), 'animals in this list:')
for item in animals:
print (' ',item)

Q9. To add an elephant, then a rhino and finally a snake to the list:

animals.append('elephant')
animals.append('rhino')
animals.append('snake')
print('There are', len(animals), 'animals in this list:')
for item in animals:
print (' ',item)

Q10. To make a copy of a list and print the copy out:

print('\n')
newAnimals = animals[:]
print('There are', len(newAnimals), 'animals in the newAnimals list:')
for item in newAnimals:
print (' ',item)

Back