Python Tuples
kodingwindow@kw:~$ python3 ... >>> days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Sunday','Friday','Saturday') >>> days[0] 'Sunday' >>> days[0:3] ('Sunday', 'Monday', 'Tuesday', 'Wednesday') >>> days[-1] 'Saturday' >>> sorted(days) ['Friday', 'Monday', 'Saturday', 'Sunday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday'] >>> max(days) 'Wednesday' >>> min(days) 'Friday' >>> len(days) 8 >>> days.count('Sunday') 2 >>> days.index('Sunday') 0 >>> days.index('Sunday',1,7)# Skipped the first occurrence 5 >>> days.index('Sunday',1,) 5 >>> del days >>> daysTraceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'days' is not defined
Unpacking a Tuple
>>> days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Sunday','Friday','Saturday') >>> (day0,day1,day2,day3,day4,day5,day6,day7)=days >>> day3 'Wednesday' >>> day7 'Saturday'
Concatenate two or more Tuples
>>> tuple1 = ('Monday', 'Tuesday', 'Wednesday', 'Thursday') >>> tuple2 = (4, 3, 6, 8, 3.14) >>> tuple1 + tuple2 ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 4, 3, 6, 8, 3.14) >>> tuple3 = ('Sunday', -2, -9.87, 'M', 'F') >>> tuple1 + tuple2 + tuple3 ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 4, 3, 6, 8, 3.14, 'Sunday', -2, -9.87, 'M', 'F')
Convert a List into Tuple using tuple() function
>>> days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday'] >>> dayslist = ['Monday', 'Tuesday', 'Wednesday', 'Thursday'] >>> dayslist[0] 'Monday' >>> dayslist.append('Sunday') >>> dayslist ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Sunday'] >>> daystuple = tuple(dayslist) >>> daystuple ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Sunday') >>> daystuple.append('Sunday')#Tuples are immutable Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append'
Convert a Dictionary into Tuple using tuple() function
>>> KV={'s1':'Linus','s2':'Thomson','s3':'Edison'} >>> KV {'s1': 'Linus', 's2': 'Thomson', 's3': 'Edison'} >>> KV['s1'] 'Linus' >>> KVtuple = tuple(KV) >>> KVtuple ('s1', 's2', 's3') >>> KVtuple = tuple(KV.items()) >>> KVtuple (('s1', 'Linus'), ('s2', 'Thomson'), ('s3', 'Edison'))
Advertisement