Topics
Tuple Creation
Tuple is very similar to a list, which contains a sequence of objects. Its main difference is it cannot be modified after creation. A tuple is created by assigning a list of comma-separated values to a variable. For clarity, it is recommended to enclose the values with the parentheses.
# create a tuple with values: 'a', 'b', 'c' >>> t1 = ('a', 'b', 'c') >>> type(t1)# create a tuple with values: 1, 2, 3, 4, 5 >>> t2 = 1, 2, 3, 4, 5 >>> t2 (1, 2, 3, 4, 5) # create an empty tuple >>> t3 = () # create a tuple with one element, # need to add a comma >>> t4 = (5,)
Accessing Values in a Tuple
Like List and String, Tuple is zero indexed. The same slicing rule applies for accessing elements within a tuple. See examples below:
>>> x = ('a', 'b', 'c', 'd', 'e') # Getting first element >>> x[0] 'a' # Getting last element >>> x[-1] 'e' # Getting second and third elements using slicing >>> x[1:3] ('b', 'c')
Modifying a Tuple
Tuple is immutable, and therefore its value cannot be modified directly. However, you can “modify” a tuple by re-assigning the value to another tuple.
>>> a = (1, 2, 3, 4, 5) >>> a[0] = 10 Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: 'tuple' object does not support item assignment # replace the first element with (10,), # and reassign the result to a new tuple >>> b = (10,) + a[1:] >>> b (10, 2, 3, 4, 5) # Not allowed to delete elements in a tuple >>> del a[0] Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: 'tuple' object does not support item deletion # You can delete the whole tuple >>> del a
Other useful tuple operations
Those list functions that does not modify the content of the list can also be used with Tuple.
>>> x = (2, 6, 3, 1, 10, 5) # get number of items in the tuple >>> len(x) 6 # get the maximum value in the tuple >>> max(x) 10 # get the minimum value in the tuple >>> min(x) 1 # get the number of 5 in the tuple >>> x.count(5) 1