September
27
Tuples
Tuple is sequence of values separated with comma and enclosed in parentheses.Tuple is very similar to List like accessing values,negative indices and slicing work same as list.
Difference between Tuples and lists are, you can not modify tuples unlike lists that why tuple is immutable object and tuples enclosed with parentheses whereas lists use square brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
>>> tup1 = ('python', 'name', 1.2, 20) # Declaring >>> tup2 = (10, 20, 30, 40); # Declaring >>> print "tup1[0]: ", tup1[0] #accessing tup1[0]: python >>> print "tup2[1:3]: ", tup2[1:3] #slicing tup2[1:3]: (20, 30) >>> tup1[1] = "second name" # You cannot update/change tuple elements Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> tup1[1] = "second name" TypeError: 'tuple' object does not support item assignment >>> >>> dir(tup1) # method present in tuples ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] >>> |
Key features of Tuple:
1 2 3 4 5 6 7 |
>>> a, b = 1, 2 >>> print "a = %s; b = %s"%(a,b) a = 1; b = 2 >>> a,b = b,a >>> print "a = %s; b = %s"%(a,b) a = 2; b = 1 >>> |
1 2 3 4 5 6 7 |
>>> tup1 = (50,); >>> tup = (50); >>> print type(tup1) <type 'tuple'> >>> print type(tup2) <type 'int'> >>> |