Python Tuple

A Python tuple could be a collection of objects which ordered and permanent. Python Tuples are groupings/sequences, a bit like Lists. The contrasts between Python tuples and Python Lists are, the tuples cannot be changed not at all like lists and tuples utilize enclosures, while lists utilize square brackets.

Creating Tuple:

Making a tuple is as basic as putting diverse comma-separated values. Alternatively, you’ll be able to put these comma-separated values between enclosures moreover.

Example is given below,

For Empty tuple,

Tuple with only one value, you have to put a comma at the end.

Accessing values in Tuple:

To get to values in tuple, utilize the square brackets for slicing beside the lists to get value accessible at that list.

#accessingtuple

tup1 = ('John, Tom, Bob');
tup2 = ( 12, 14, 16, 18, 20 ); 
print ("tup1[1]: ", tup1[1])
print ("tup2[1:4]: ", tup2[1:4])

Updating Tuple:

Tuples are permanent which implies you cannot upgrade or alter the values of tuple components. But we are able to require parcels of existing tuples to form unused tuples. as given in example below,

tup1 = (77, 88, 99);
tup2 = ('Bob', 'Alice');

#to update
#tup1[0] = 100;
#This action is not valid for tuples
#now we'll create a new tuple 
tup3 = tup1 + tup2;
print tup3;

Deleting Tuple element:

In tuple, we can’t remove any individual element, to delete any element from tuple we’ll make another tuple containing undesired elements in it and then by using Del statement, we can remove that element.

#Deleting tuples
tuple = ('A','E','I','O','U')

#can't delete items
#TypeError: 'tuple' object doesn't support item deletion
#del tuple[3]

#Can delete an entire tuple
del tuple

#NameError: name 'tuple' is not defined
print(tuple)

Basic Tuples Operations:

Tuples respond to the concatenation(+) and repetition (*) operators as strings; but the result creates a new tuple, not a string. Other than that tuple respond to all other operations. The table given below will show the basic operations used in the tuple.

ExpressionDescriptionOutput
len ([a, b, c])Length3
[a, b, c]+[x, y, z]Concatenation[a, b, c, x, y, z]
u in [u, v, w ]MembershipTrue
[KARL]*3RepetitionKARL,KARL.KARL
for y in [l, m, n]: print y
Iterationl, m, n

Built-in Tuple Functions:

Following table is consist of Built-in Tuple functions,

FunctionDescription
tuple(seq)Converts a list into tuple
max(tuple)Returns item from the tuple with max value.
len(tuple)Gives the total length of the tuple.
min(tuple)Returns item from the tuple with min value.
cmp(tuple1, tuple2)Compares elements of both tuples.