Tuples in python
A tuple is a sequence of ordered elements which is imputable. The most important difference between list and tuple is that: tuple uses parenthesis whereas the list uses the square bracket. Values are put inside parenthesis separated by a comma.
For Example:
tuple1 = ('man', 'women', 2102, 1000);
tuple2 = (1, 2, 3 );
How to excess values in Tuples:
In order to access the value of the tuple, you need to use the square brackets along with the index position.
Example:
this1 = ("apple", "graphs ", "cherry")
print(this1[1])
this2 = ("apple", "banana", "cherry", "melon", "mango","graphes")
print(this2[1:5])
How to update the values in tuples:
Here tuple is immutable so we can’t alter the value in tuples as in the list it was possible.
Example:
tup1 = (123, 34.5632);
tup2 = ('abcdef', 'xyzabcde');
# Following code is invalid because tuple is immutable means we cannot change the value
# tup1[1] = 89;
# We can create the new tuple using + operator
tup3 = tup1 + tup2;
print tup3;
How to delete values in Tuples:
Index deletion is not performed in tuple, on the other hand a whole tuple can be deleted easily.
Example:
tuplis1 = ('Math', 'physics','chemistry', 1997, 2000);
print tuplis1;
del tuplis1;
print "After deleting tuplis1 : ";
print tuplis1;
Basic tuples operations and methods:
We can also perform operations like concatenation and iteration using tuples like lists. Basically, tuples use parenthesis and produce output of a new tuple.
| Python Expression using tuple | Results Output | Description Operation |
|---|---|---|
| len((1, 2, 3, 4, 5)) | 5 | return Length of elements |
| (1, 2, 3, 7) + (4, 5, 6) | (1, 2, 3,7, 4, 5, 6) | Perform Concatenation |
| (‘Good’) * 4 | (‘Good’, ‘Good’, ‘Good’, ‘Good’) | Perform Repetition |
| 3 in (1, 2, 3) | True | Membership |
| for x in (7, 5, 2): print x, | 752 | Perform Iteration |
Functions in Python:
1.len()
This method will return the number of elements in the tuples.
tuple1, tuple2 = (123, 'xyz', 'zara'), (4, 'abc')print(First tuple length of tuple1 : ", len(tuple1))print("Second tuple length of tuple2: ", len(tuple2))
2.max()
This method will return the maximum value element form the tuples.
tuplea, tuplea = (123, 'xyz', 'amit', 'abc'), (123, 1700, 200)
print ("Max value element : ", max(tuplea))
print ("Max value element : ", max(tupleb))
3.cmp()
This method will compare two tuple and return -1, 0 ,1:
if a<b
return -1
if a=b
return 0
if a>b
return 1
tup1, tup2 = (123, 'xyz'), (456, 'abc')print (cmp(tup1, tup2))print (cmp(tup2, tup1)))tup3 = tup2 + (786,);print (cmp(tup, tup3))
4.min()
This method will return the min value element form the tuple.
tupla, tuplb = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)print ("min value element : ", min(tupla))print ("min value element : ", min(tuplb))
5.tuple()
This method will convert the list to tuple.
lst1 = [123, 'swt', 'zara', 'abc']NewTuple = tuple(lst1)print ("Tuple elements : ", NewTuple)
