Contents
Python Tuple
In Python, Tuple is a collection of items. In Python Tuple, items are ordered, and therefore can be accessed using index.
Also, an important property to note about Python Tuple is that, it is immutable. You cannot change the items of a tuple in Python.
But, if it is really necessary for you to change a tuple, you may convert the tuple to a list, modify it, and convert back to a list. This is only a workaround to modify a tuple.
Examples
A Python Tuple can contain a definite number of items belonging to different datatypes.
Following are some of the examples for Tuples in Python.
tuple1 = (14, 52, 17, 24)
tuple2 = ('Hello', 'Hi', 'Good Morning')
tuple3 = (1, 'Tony', 25)
Run Create a Tuple
To create a tuple, you can provide the comma separated items enclosed in parenthesis or use tuple() builtin function. tuple() accepts an iterable and converts the iterable into tuple.
In the following program, we will create a tuple in two ways: using parenthesis and tuple() builtin function.
Python Program
tuple1 = ('a', 'e', 'i', 'o', 'u')
tuple2 = tuple(['a', 'e', 'i', 'o', 'u'])
Run Access Tuple Items using Index
As Tuple items are ordered, you can access them using index as that of items in a Python List.
Python Program
tuple1 = (14, 52, 17, 24)
print(tuple1[1])
print(tuple1[3])
Run Output
52
24
Python Tuple Length
Like any other collection in Python, you may use len() builtin function to get the length of a tuple.
Python Program
tuple1 = (14, 52, 17, 24)
print( len(tuple1) )
Run Output
4
Iterate over items of Python Tuple
You can iterate over Python Tuple’s items using for loop.
Python Program
tuple1 = (14, 52, 17, 24)
for item in tuple1:
print(item)
Run Output
14
52
17
24
Or you can also use while loop with tuple length and index to iterate over tuple’s items.
Python Program
tuple1 = (14, 52, 17, 24)
index = 0
while index<len(tuple1):
print(tuple1[index])
index = index + 1
Run Output
14
52
17
24
Summary
In this Python Tutorial, we learned what a Tuple is in Python and how to define and access it in different ways.