Tuples

   Tuples are python data structures similar to lists. A tuple is composed of values separated by commas and enclosed within parenthesis. Like comparison to remember that lists are enclosed in brackets.

Tuple example:

myTuple=('mnp', 5, 145.34, False, 'Blue sky')
print(myTuple)

#output
(False, 'Blue sky', 145.34, 5, 'mnp')


   Tuple elements are ordered and immutable (tuple is like a read-only list). Tuple elements are accessed similar like lists. Below are examples of accessing tuple elements:

myTuple=('mnp', 5, 145.34, False, 'Blue sky')


print(myTuple[1])     #accessing by index

#output

5


print(myTuple[2:4])     #accessing with slice notation

#output

(145.34, False)


print(myTuple[1:])     #accessing with slice notation

#output

(5, 145.34, False, 'Blue sky')


   Tuples elements are immutables (tuple is like a read-only list). If we try to modify an element from tuple similar like we do in lists case we will get an error. For example: 

myTuple = (5, 'test123', 23.54, False, 'xyz')

myTuple[0]=10


#output

Traceback (most recent call last):

  File "<pyshell#1>", line 1, in <module>

    myTuple[0]=10

TypeError: 'tuple' object does not support item assignment


   Even if tuple is immutable, a tuple can contain like elements a list, elements of which can be modified. For example:

tuple123 = (10, [12, 7.5, True], 34.54, 'abc')

tuple123[1][0]=11

print(tuple123)


#output

(10, [11, 7.5, True], 34.54, 'abc')

Here we see tuple123 contain like second element a list, i.e. [12, 7.5, True], means tuple123[1]= [12, 7.5, True]. There tuple123[1][0] access first element of list [12, 7.5, True]


In previous example we have a nested list in a tuple, or a tuple that contains elements like a list. 

Obvious we can have a tuple that contains other tuple(s) and so on..., nested tuples.