Python Tuples
Python Tuples
http://www.tuto rialspo int.co m/pytho n/pytho n_tuple s.htm Co pyrig ht © tuto rials po int.co m
A tuple is a sequence of immutable Python objects. T uples are sequences, just like lists. T he only difference is
that tuples can't be chang ed i.e., tuples are immutable and tuples use parentheses and lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values and optionally you can put these
comma-separated values between parentheses also. For example:
tup1 = ();
T o write a tuple containing a sing le value you have to include a comma, even thoug h there is only one value:
tup1 = (50,);
Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.
#!/usr/bin/python
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples:
T uples are immutable which means you cannot update them or chang e values of tuple elements. But we able to
take portions of an existing tuples to create a new tuples as follows. Following is a simple example:
#!/usr/bin/python
T o explicitly remove an entire tuple, just use the del statement. Following is a simple example:
#!/usr/bin/python
print tup;
del tup;
print "After deleting tup : "
print tup;
T his will produce following result. Note an exception raised, this is because after del tup tuple does not exist
any more:
In fact, tuples respond to all of the g eneral sequence operations we used on string s in the prior chapter :
No Enclosing Delimiters:
Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists,
parentheses for tuples, etc., default to tuples, as indicated in these short examples:
#!/usr/bin/python
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total leng th of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.