Python Tuple is a collection of items.
Python Tuple is Ordered
Items in a Tuple are stored in an order. Therefore, we can access items in a Tuple based on index.
Python Tuple is Immutable
We cannot modify a Tuple. In other words, we cannot add items to a Tuple, cannot update items of a Tuple using index, or cannot remove items from a Tuple.
Create Python Tuple
To create a Tuple in Python, use parenthesis
() as shown in the following example.
tuple_1 = (item_1, item_2, item_3)
Place as many items as required inside curly braces and assign it to a variable.
We can also use tuple() builtin function to create a Python Tuple. Pass an iterable to tuple() function, and it returns a Tuple created from the items in that iterable.
tuple_1 = tuple(iterable)
In the following program, we create two tuples: tuple_1 and tuple_2 using parenthesis and tuple() function respectively.
#create tuple using parenthesis tuple_1 = (2, 4, 6) print(tuple_1) #create tuple using tuple() builtin function x = ['a', 'b', 'c'] tuple_2 = tuple(x) print(tuple_2)Try Online
(2, 4, 6) ('a', 'b', 'c')
Access Items of Python Tuple
Python Tuple is ordered and an iterable. Therefore, we can access items using index, and iterate over items using for loop or while loop.
Example – Access using Index
In the following program, we create a tuple with three items, and print items one at a time by accessing them using index.
tuple_1 = (2, 4, 6) print(tuple_1) print(tuple_1) print(tuple_1)Try Online
2 4 6
Example – Access using For Loop
In the following program, we create a tuple with three items, and print items one at a time by accessing them using for loop.
tuple_1 = (2, 4, 6) for item in tuple_1: print(item)Try Online
2 4 6
In this Python Tutorial, we learned what Python Tuples are, how to create them, how to access items in a Tuple, and methods of Python Tuple.