pythonlistelementreassign

Trouble modifying a value in a list


Using Python 3.11.1 in JupyterLab Version 3.5.2

I,m getting this error message and I'm not sure how. list is a list with 6 items within it. As you can see Dad is the first item. I am trying to reassign this value to Mike. The error message is calling this a tuple, but it's a list.

Help Please!

list = "Dad", "Bard", "Tammy", "Sean", "Chance", "Gabe"

print(list)

print(list[0])

list[0] = "Mike"

('Dad', 'Bard', 'Tammy', 'Sean', 'Chance', 'Gabe') Dad


TypeError                                 Traceback (most recent call last)
Cell In[3], line 7
      3 print(list)
      5 print(list[0])
----> 7 list[0] = "Mike"

TypeError: 'tuple' object does not support item assignment

I found multiple examples online that showed the reassignment of a list item, and I duplicated them exactly, but I still got this error message.


Solution

  • You're not creating a list, you're creating a tuple. The syntax for a list uses brackets. A comma-separated "list" (not list) of items, without brackets, is a tuple. (It's also not a great idea to use a builtin name as a variable.)

    my_list = ["Dad", "Bard", "Tammy", "Sean", "Chance", "Gabe"]
    my_list[0] = "Mike"
    print(my_list)