Python Tuple
Tuple is an ordered collection of data or elements which are immutable and placed within the round brackets.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print(fruits)
Output
Access Tuple Items
To access the items or elements of a tuple, you can simply refer to the item index number.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print(fruits[2])
Output
Access Tuple Items Using Negative Index
The negative index starts from the last item of a tuple in Python.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print("Item at index -1 is " + fruits[-1])
print("Item at index -2 is " +fruits[-2])
print("Item at index -3 is " +fruits[-3])
Output
Item at index -2 is apple
Item at index -3 is guava
Access Tuple Items Using Range Index
Items of a tuple can also be accessed by specifying range of indexes, the start index and the end index separated by colon.
Syntax
tuple[start index : end index]
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print(fruits[1:3])
Output
A tuple items can also be accessed using negative index with range. Negative index starts the search from the last index of a tuple.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print(fruits[-3:-1])
Output
Loop Through Tuple
Items of a tuple can also be accessed by using the for loop.
Syntax
tuple[start index : end index]
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
for i in fruits:
print(i)
Output
grapes
guava
apple
watermelon
Check if Item Exists in Tuple
To check for existence of items in a tuple, you can use the in keyword.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
if "apple" in fruits:
print("apple exists")
Output
Tuple Length
To get the length of a tuple, you can use the len() function.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print(len(fruits))
Output
Tuple Add Items
Tuple is immutable which means after the tuple is created, new items in tuple cannot be added and existing items cannot be deleted. The example below will show error.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
fruits[2] = "banana"
Create Tuple using tuple() constructor
A tuple can also be created using the tuple() constructor.
Example
colors = tuple(("white", "green", "yellow", "blue", "red"))
print(colors)
Output
Join Two Tuples
In Python, two tuples can be added together using the + operator.
Example
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
colors = ("white", "green", "yellow", "blue", "red")
tuples = fruits + colors
print(tuples)