Lists can be changed after creation.
Assigning to an index replaces that element:
colors = ["red", "green", "blue"]
colors[1] = "yellow"
print(colors)
Output:
['red', 'yellow', 'blue']
append adds an element at the end. It is called with a dot on the list itself — this form is called a method:
colors.append("black")
print(colors)
Output:
['red', 'yellow', 'blue', 'black']
insert places an element at a given index, pushing later elements one step right:
colors.insert(0, "white")
print(colors)
Output:
['white', 'red', 'yellow', 'blue', 'black']
The starter code creates guests with two names.
"Alan"."Edsger"."Barbara" at index 1.guests. The final list is ['Edsger', 'Barbara', 'Grace', 'Alan'].Run your code to see the output, then press Submit.
import unittest
class TestChangingLists(unittest.TestCase):
def test_final_list_is_correct(self):
self.assertEqual(guests, ["Edsger", "Barbara", "Grace", "Alan"])
guests = ["Ada", "Grace"]
guests.append("Alan")
guests[0] = "Edsger"
guests.insert(1, "Barbara")
print(guests)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.