Access Tuples In Python
We are going to learn Python tuples access with examples in this article, in hopes that it will be useful for education.
Python Access Tuples Items
When working with Python access tuples, you can access tuple items by their index number, enclosed in square brackets :
In the tuple, print the fourth item:
Reminder: It is important to note that the first item has index 0.
Range of Indexes
The Python access tuples allows you to set a starting point and an end point for a range of indexes.
The returned tuple contains all items in the specified range if the range is defined.
The fourth, fifth, and sixth items should be returned as follows:
Reminder: It should be noted that the search will start at index 3 (included) and end at index 6 (not included).
You must remember that the index of the first item is 0.
In the absence of a start value, the range will start at the first item in the list.
In this example, items are returned from the beginning to, but not including, “Spain”:
If the range doesn’t contain a value at the end, it will go on to the end of the list.
In this example, we return the items from “Brazil” to the end:
Python access tuples negative indexing means starting from the end.
- The last item is numbered -1,
- The -2 indicates the second last item, etc.
Take the last item from the tuple and print it:
Check if Item Exists
If we are talking about Python access tuples, we can use the in keyword to check if an item exists.
Verify that “Germany” appears in the list:
Range of Negative Indexes
In Python access tuples, specify negative indices if you would like to start searching from the end.
Using this example, we return all items from “Brazil” (-7) to, but exclude “Italy” (-1):