# create tuplepoint = (3, 5)rgb = (255, 128, 0)single = (42,)#ans: note comma for single elementempty = ()
# indexing tuplespoint = (3, 5)point[0]#ans: 3point[-1]#ans: 5
# unpack valuesx, y = (3, 5)#ans: x=3, y=5r, g, b = (255, 128, 0)#ans: r=255, g=128, b=0
# cannot modifypoint = (3, 5)#ans: point[0] = 10 # TypeError
# concatenationtuple1 = (1, 2)tuple2 = (3, 4)tuple1 + tuple2#ans: (1, 2, 3, 4)#ans: repetition(1, 2) * 3#ans: (1, 2, 1, 2, 1, 2)
# countnumbers = (1, 2, 3, 2, 4)numbers.count(2)#ans: 2#ans: indexnumbers.index(3)#ans: 2
# single element tuple?x = (5)type(x)#ans: <class 'int'>y = (5,)type(y)#ans: <class 'tuple'>
# tuple unpacking?a, b = (10, 20)#ans: a=10, b=20
# can you modify?t = (1, 2, 3)t[0] = 10#ans: TypeError (tuples are immutable)
# tuple slicing?t = (1, 2, 3, 4, 5)t[1:4]#ans: (2, 3, 4)
# nested tuple?t = ((1, 2), (3, 4))t[0][1]#ans: 2
# tuple with list?t = (1, [2, 3], 4)t[1].append(5)#ans: t is (1, [2, 3, 5], 4)
# empty tuple length?t = ()len(t)#ans: 0
# tuple from string?t = tuple("abc")#ans: ('a', 'b', 'c')
# comparing tuples?(1, 2) == (1, 2)#ans: True(1, 2) < (1, 3)#ans: True
# tuple membership?3 in (1, 2, 3)#ans: True
Google tag (gtag.js)