Back

'Modifying' and examining tuples - Answers

We are using the following tuple for the questions:

monsters=('goblin', 'orc', 'evil pixie', 'ogre', 'firedog', 'mummy', 'witch')

Q1.

monsters.append("genie")
print (monsters)

AttributeError: 'tuple' object has no attribute 'append'.

This failed because tuples are immutable. Once created, they can't be modified.

Q2.

monsters.remove("evil pixie")
print(monsters)

AttributeError: 'tuple' object has no attribute 'remove'.

This failed because tuples are immutable. Once created, they can't be modified.

Q3.  

print (monsters.index('mummy'))

5, because 'mummy' is at position 5 in the tuple.

Q4. 

print (monsters.index('goblin'))

0, because 'goblin' is at position 0 in the tuple.

Q5. 

print ("orc" in monsters)

True, because 'orc' is in the tuple.

Q6. 

print ("undead" in monsters)

False, because 'undead' is not in the tuple.

Q7. print (monsters*2)

('goblin', 'orc', 'evil pixie', 'ogre', 'firedog', 'mummy', 'witch', 'goblin', 'orc', 'evil pixie', 'ogre', 'firedog', 'mummy', 'witch')

Q8. 

monsters2 = monsters + "undead"
print (monsters2)

TypeError: can only concatenate tuple (not "str") to tuple.

Q9.

monsters_temp = ('undead')
monsters2 = monsters + monsters_temp
print (monsters2)

TypeError: can only concatenate tuple (not "str") to tuple. 

monsters_temp is a tuple holding just one element only, a string. The rule for tuples in Python is that if there is only one element in the tuple, it must have a comma after it. We can see this in the next example.

Q10.

monsters_temp = ('genie',)
monsters2 = monsters + monsters_temp
print (monsters2)

('goblin', 'orc', 'evil pixie', 'ogre', 'firedog', 'mummy', 'witch', 'genie').

Because we remembered to put a comma after the tuple called monsters_temp (because it contains just one element), we can concatenate these two tuples to create a brand new tuple called monsters2.

Q11.

monsters_temp = ('zombie',)
monsters2 = monsters + monsters_temp
print (monsters2)
print (len(monsters2))

('goblin', 'orc', 'evil pixie', 'ogre', 'firedog', 'mummy', 'witch', 'zombie')
8

Back