Tutorial by Examples

x = (1, 2, 3) x[0] # 1 x[1] # 2 x[2] # 3 x[3] # IndexError: tuple index out of range Indexing with negative numbers will start from the last element as -1: x[-1] # 3 x[-2] # 2 x[-3] # 1 x[-4] # IndexError: tuple index out of range Indexing a range of elements print(x[:-1]) # (1,...
One of the main differences between lists and tuples in Python is that tuples are immutable, that is, one cannot add or modify items once the tuple is initialized. For example: >>> t = (1, 4, 9) >>> t[0] = 2 Traceback (most recent call last): File "<stdin>", l...
hash( (1, 2) ) # ok hash( ([], {"hello"}) # not ok, since lists and sets are not hashabe Thus a tuple can be put inside a set or as a key in a dict only if each of its elements can. { (1, 2) } # ok { ([], {"hello"}) ) # not ok
Syntactically, a tuple is a comma-separated list of values: t = 'a', 'b', 'c', 'd', 'e' Although not necessary, it is common to enclose tuples in parentheses: t = ('a', 'b', 'c', 'd', 'e') Create an empty tuple with parentheses: t0 = () type(t0) # <type 'tuple'> To crea...
Tuples in Python are values separated by commas. Enclosing parentheses for inputting tuples are optional, so the two assignments a = 1, 2, 3 # a is the tuple (1, 2, 3) and a = (1, 2, 3) # a is the tuple (1, 2, 3) are equivalent. The assignment a = 1, 2, 3 is also called packing because it...
Reverse elements within a tuple colors = "red", "green", "blue" rev = colors[::-1] # rev: ("blue", "green", "red") colors = rev # colors: ("blue", "green", "red") Or using reversed (reversed gives an it...
Tuples support the following build-in functions Comparison If elements are of the same type, python performs the comparison and returns the result. If elements are different types, it checks whether they are numbers. If numbers, perform comparison. If either element is a number, then the other...

Page 1 of 1