Login

Back

List methods

 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. Add a zebra to the end of the list.
Q3. Add another zebra to the list so it is the third item along (remember, index = 2).
Q4. Count the number of zebras in the list and display an appropriate message.
Q5. Display a message that states what position 'eagle' is at.
Q6. Print out the list in alphabetical order.
Q7. Print out the list in reverse alphabetical order.
Q8. Use the Python documentation and the Internet to find other methods to help you. Remove all the items from the list so it is an empty list. Print out the length and contents, to prove it is empty.
Q9. Add an elephant, then a rhino and finally a snake to the list. Print out the length and the contents of the final list.
Q10. Make an exact copy of the final list. Call it 'newAnimals'.