Changing Lists

Changing Lists

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']

Exercise

The starter code creates guests with two names.

  1. Append "Alan".
  2. Replace the first element with "Edsger".
  3. Insert "Barbara" at index 1.
  4. Print guests. The final list is ['Edsger', 'Barbara', 'Grace', 'Alan'].

Run your code to see the output, then press Submit.

Tests

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)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.