Overview
Python tuple items are indexed and can be accessed by referring to their index number.
Accessing Items
The following will print the second item in the tuple.
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
print(my_tuple[1]) #Maserati
Note
Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.
Negative Indexing
Negative indexing means start from the end and count backwards when accessing items.
- -1 refers to the last item
- -2 refers to the second last item
- etc.
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
print(my_tuple[-1]) #Alfa Romeo
Range of Indexes
A range of indexes can be included by specifying where to start and where to end the range.
When specifying a range, the returned value will be a new list with the specified items.
my_tuple = ("Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche")
print(my_tuple[1:3]) #('Ferrari', 'Maserati')
Note
The last number in a range is NOT INCLUSIVE!
By leaving out the start value, the range will start at the first item.
my_tuple = ("Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche")
print(my_tuple[:3]) #('Lamborghini', 'Ferrari', 'Maserati')
By leaving out the end value, the range will go on all the way to the last item.
my_tuple = ("Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche")
print(my_tuple[2:]) #('Maserati', 'Alfa Romeo', 'Porsche')
Range of Negative Indexes
Specify negative indexes to start the range search from the end of the tuple.
my_tuple = ("Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche")
print(my_tuple[-3:-1]) #('Maserati', 'Alfa Romeo')
Note
Even using negative indexes, the last number in a range is NOT INCLUSIVE!
Check if an Item Exists
To determine if a specified item is present in a tuple use the “in” keyword.
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
if "Maserati" in my_tuple:
print("'Maserati' is in the tuple")
- The item is case sensitive
- The item must match exactly
Output:
'Maserati' is in the tuple
Python Notes:
- The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
- Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
- Python string methods return new values, and DO NOT change the original string
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.