List operations
In this section, you will learn slicing, accessing, adding, deleting, and updating the values in a list.
Accessing list values
In order to access list values, use list names with positional index in square brackets. For example, consider the following code snippet:
>>> Avengers = ['hulk', 'iron-man', 'Captain', 'Thor'] >>> Avengers[0] 'hulk' >>> Avengers[3] 'Thor' >>> Avengers[-1] 'Thor' >>> Avengers[4] Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> Avengers[4] IndexError: list index out of range
If the desired index is not found in the list, then the interpreter throws IndexError
.
Slicing the list
The slicing of a list is the same as we did in tuples. See the syntax:
<list-name>[start : stop : step]
See the example:
>>> Avengers[1:3] ['iron-man', 'Captain'] >>> Avengers[:4] ['hulk', 'iron-man', 'Captain', 'Thor'] >>> Avengers[:] ['hulk', 'iron...