List Indexes
List Indexes
Each item/element in a list has its own unique index. This index can be used to access any particular item from the list. The first item has index [0], second item has index [1], third item has index [2] and so on.
Example:
Accessing list items:
Positive Indexing:
As we have seen that list items have index, as such we can access items using these indexes.
Example:
Output:
Negative Indexing:
Similar to positive indexing, negative indexing is also used to access items, but from the end of the list. The last item has index [-1], second last item has index [-2], third last item has index [-3] and so on.
Example:
Output:
Check for item:
We can check if a given item is present in the list. This is done using the in keyword.
Output:
Output:
Range of Index:
You can print a range of list items by specifying where do you want to start, where do you want to end and if you want to skip elements in between the range.
Syntax:
List[start : end : jumpIndex]
Note: jump Index is optional. We will see this in given examples.
Example: printing elements within a particular range:
Output:
Here, we provide index of the element from where we want to start and the index of the element till which we want to print the values.
Note: The element of the end index provided will not be included.
Example: printing all element from a given index till the end
Output:
When no end index is provided, the interpreter prints all the values till the end.
Example: printing all elements from start to a given index
Output:
When no start index is provided, the interpreter prints all the values from start up to the end index provided.
Example: print alternate values
Output:
Here, we have not provided start and index, which means all the values will be considered. But as we have provided a jump index of 2 only alternate values will be printed.
Example: printing every 3rd consecutive withing given range
Output:
Here, jump index is 3. Hence it prints every 3rd element within given index.