Problem Context
You have a list of your favourite Marvel super heroes. Review the initial code below and then answer the questions that follow by writing the correct Python code.
# A list of Marvel super heros
heros = ['spider man', 'thor', 'hulk', 'iron man', 'captain america']
Quiz Questions
1. What Python code finds the length of the list?
Show Answer & Explanation
Correct Code: len(heros)
Explanation: The built-in len() function returns the number of items in a list. In this case, it will return 5.
2. What Python code adds 'black panther' at the end of this list?
Show Answer & Explanation
Correct Code: heros.append('black panther')
Explanation: The .append() method adds one item to the very end of the list.
3. You need to move 'black panther' (added in Q2) to be after 'hulk'. What two commands (separated by a semicolon) do you use?
Show Answer & Explanation
Correct Code: heros.remove('black panther');heros.insert(3,'black panther')
Explanation: This is a two-step process:
heros.remove('black panther')finds and removes the first occurrence of 'black panther' (which is at the end).heros.insert(3, 'black panther')adds the item at index 3. Since 'hulk' is at index 2, this places it right after him.
4. What *one line* of code removes 'thor' and 'hulk' and replaces them with 'doctor strange'?
Show Answer & Explanation
Correct Code: heros[1:3] = ['doctor strange']
Explanation: This uses list slicing. heros[1:3] refers to the slice starting at index 1 ('thor') and ending *before* index 3 ('hulk'). This effectively selects ['thor', 'hulk']. By assigning a new list ['doctor strange'] to this slice, you replace both items with the one new item.
5. What code sorts the list in alphabetical order?
Show Answer & Explanation
Correct Code: heros.sort()
Explanation: The .sort() method sorts the list in-place (modifies the original list) in ascending alphabetical order.
0 Comments