Access Tuple Items

 

What You'll Learn: In this tutorial, you'll discover how to access items in a tuple using their index numbers. Tuples are like lists, but they are immutable (unchangeable).

Access Tuple Items by Index

You can access tuple items by referring to their index number, inside square brackets [].

Example Code:

python
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Output: banana

What's Happening Here?

  • thistuple[1] accesses the second item in the tuple (index starts at 0).

Negative Indexing

Negative indexing means starting from the end of the tuple. -1 refers to the last item, -2 to the second last, and so on.

Example Code:

python
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

Output: cherry

What's Happening Here?

  • thistuple[-1] accesses the last item in the tuple.

Range of Indexes

You can specify a range of indexes to return a new tuple with the specified items.

Example Code:

python
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

Output: ('cherry', 'orange', 'kiwi')

What's Happening Here?

  • thistuple[2:5] returns items from index 2 to 4 (index 5 is not included).

Range from Start

By leaving out the start value, the range starts at the first item.

Example Code:

python
print(thistuple[:4])

Output: ('apple', 'banana', 'cherry', 'orange')

Range to End

By leaving out the end value, the range goes to the end of the tuple.

Example Code:

python
print(thistuple[2:])

Output: ('cherry', 'orange', 'kiwi', 'melon', 'mango')

Range of Negative Indexes

You can specify negative indexes to start the search from the end of the tuple.

Example Code:

python
print(thistuple[-4:-1])

Output: ('orange', 'kiwi', 'melon')

Check if Item Exists

To determine if a specified item is present in a tuple, use the in keyword.

Example Code:

python
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
    print("Yes, 'apple' is in the fruits tuple")

Output: Yes, 'apple' is in the fruits tuple

Try It Yourself: Fun Exercises

  1. Find Your Favorite Fruit:
    • Create a tuple of your favorite fruits.
    • Use both positive and negative indexing to access different fruits.
  2. Check for a Fruit:
    • Write a tuple of fruits.
    • Use the in keyword to check if a specific fruit is in the tuple.

Summary:

In this Python tutorial, we learned how to access items in a tuple using index numbers, including positive and negative indexing, and ranges. We also learned how to check if an item exists in a tuple using the in keyword. Keep experimenting and have fun with tuples in Python!