Tuples are another container type extremely similar in nature to lists. The only visible difference between tuples and lists is that tuples use parentheses and lists use square brackets. Functionally. there is a more significant difference, and that is the fact that tuples are immutable.
Our usual modus operandi is to present the operators and built-in functions for the more general objects, followed by those for sequences and conclude with those applicable only for tuples, but because tuples share so many characteristics with lists, we would be duplicating much of our description from the previous section. Rather than providing much repeated information, we will differentiate tuples from lists as they apply to each set of operators and functionality, then discuss immutability and other features unique to tuples.
How to Create and Assign Tuples
Creating and assigning lists are practically identical to lists, with the exception of empty tuples. These require a trailing comma ( , ) enclosed in the tuple delimiting parentheses ( ( ) ).
>>> aTuple = (123,'abc',4.56,['inner','tuple'],7-9j) >>> anotherTuple = (None,'something to see here') >>> print aTuple (123, 'abc', 4.56, ['inner', 'tuple'], (7-9j)) >>> print anotherTuple (None, 'something to see here') >>> emptiestPossibleTuple = (None,)
How to Access Values in Tuples
Slicing works similar to lists: Use the square bracket slice operator ([ ]) along with the index or indices.
>>> aTuple (123, 'abc', 4.56, ['inner', 'tuple'], (7-9j)) >>> aList[1:4] [93, 99, 'time'] >>> aTuple[:3] (123, 'abc', 4.56) >>> aTuple 'tuple'