MyAI

Tuples

Tuple is one of the built-in data types in Python. A Python tuple is a sequence of comma separated items, enclosed in parentheses (). The items in a Python tuple need not be of same data type.

In Python, tuple is an immutable data type. An immutable object cannot be modified once it is created in the memory.

You can use a work-around to update a tuple. Using the list() function, convert the tuple to a list, perform the desired append/insert/remove operations and then parse the list back to tuple object.

Unpack Tuple Items

The term “unpacking” refers to the process of parsing tuple items in individual variables.

ex:

tup1 = (10,20,30)
x, y, z = tup1
print ("x: ", x, "y: ", "z: ",z) -> x: 10, y: 20, z: 23

use the “” symbol is used for unpacking. Prefix “” to “y”, as shown below −

ex:

tup1 = (10,20,30, 40, 50, 60)
x, *y, z = tup1
print ("x: ",x, "y: ", y, "z: ", z) -> x: 10 y: [20, 30, 40, 50] z: 60
mytuples = ('Test','Tost',1984,'Test')
#Tuples can not be changed or altered
print(mytuples)
print(type(mytuples))
print(len(mytuples))

print(mytuples[0])
print(mytuples[-1])

print(mytuples.count('Test'))
print(mytuples.index('Test1'))

Result:

('Test', 'Tost', 1984, 'Test')
< class 'tuple'>
4
Test
Test
2
Traceback (most recent call last):
File "/home/sunil/Desktop/Sunil/MyAutomation/Python/16-tuples.py", line 11, in <module>
    print(mytuples.index('Test1'))
        ^^^^^^^^^^^^^^^^^^^^^^^
ValueError: tuple.index(x): x not in tuple

Main Page   Next Chapter: Python - Sets