Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Changing List Elements

You can also change an element of a list. Write the list's name and the index in square brackets, as when you read the element, and assign it a new value with =, just as you would assign a value to a variable:

resolutions = ["Keep a diary", "Take a falconry course", "Learn to juggle"]
resolutions[1] = "Take a painting course"
print(resolutions)

This prints:

['Keep a diary', 'Take a painting course', 'Learn to juggle']

The element at index 1 now has a new value, and the old one is gone. The other elements stay as they were. An element of a list works like a variable, so += works too: scores[0] += 5 adds 5 to the first element of the list scores.

You can only change an element that exists. Assigning to an index past the end of the list doesn't add a new element:

numbers = [1, 2, 3]
numbers[3] = 4

The program ends with this error:

Traceback (most recent call last):
  File "<exec>", line 2, in <module>
IndexError: list assignment index out of range

This time, the error message talks about a list assignment index: the index you assigned a value to. You'll learn how to add an element to the end of a list in a moment.

Instructions

  1. 1

    Tim has moved to another team, and Daniel has taken his place. Below the print(), change the second element of colleagues to "Daniel".

  2. 2

    Then print colleagues again. The output now shows the list before and after the change.

Back

4/12

  1. 1. Introduction to Lists
  2. 2. Creating Lists
  3. 3. Accessing List Elements
  4. 4. Changing List Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: append()
  7. 7. Removing Elements: pop()
  8. 8. Removing by Value: remove()
  9. 9. Searching a List: in
  10. 10. Nested Lists
  11. 11. Characters of a Text
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.