4. mylist = new_list_element
In the following example, the element at index 1 (the string 'eggs') is replaced with the string "lovely spam".
>>> L = ['spam', 'eggs', 'ham'] >>> L = 'lovely spam' >>> L
You can't assign to an index number that doesn't exist. Python raises an indexError, as shown here:
>>> L = 'green eggs' Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range
To add items to the end of a list, use the append() method:
Was this article helpful?