On the same line type and the new list element so your line looks something like this

4. mylist[1] = 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[1] = 'lovely spam' >>> L

You can't assign to an index number that doesn't exist. Python raises an indexError, as shown here:

>>> L[3] = '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?

0 0

Post a comment