Page 350 - Computer Science Class 11 With Functions
P. 350

>>> day = 30, 'September', 1987
         >>> myBday = day
         >>> myBday
              (30, 'September', 1987)
         >>> bDay, bMonth, bYear = 30, 'September', 1987
         >>> bDay, bMonth, bYear
              (30, 'September', 1987)
         >>> bDay, bMonth, bYear = (30, 'September', 1987)
         >>> bDay, bMonth, bYear
              (30, 'September', 1987)
         >>> (bDay, bMonth, bYear) = 30, 'September', 1987
         >>> bDay, bMonth, bYear
              (30, 'September', 1987)
         >>> (bDay, bMonth, bYear) = (30, 'September', 1987)
         >>> bDay, bMonth, bYear
              (30, 'September', 1987)
        Note that in each of the above examples, the tuple on the right hand side of the assignment operator is assigned to
        the tuple on the left hand side.

        13.7.3 Indexing

        We are already familiar with indexing. Indeed, indexing may also be applied to tuples. A tuple is an immutable object
        and an attempt to substitute an element of a tuple by another value yields type error because the tuple does not
        support assignment to its elements.
        Example
         >>> bDate = (30,'September',1987)
         >>> len(bDate)
              3
         >>> bDate[:-1]
              (30, 'September')
         >>> bDate[0] = 20
              Traceback (most recent call last):
                File '<pyshell#213>', line 1, in <module>
                  bDate[0] = 20
              TypeError: 'tuple' object does not support item assignment
        13.7.4 Slicing
        We are already familiar with slicing in the context of strings and lists. Slicing is also applicable to tuples. For example,

         >>> myTuple = (22, 30, 'Hello', 2.4, 2, 'Python', (890,900), 45)

         >>> myTuple[1:4]  # yields a tuple comprising 2nd to 4th element
              (30, 'Hello', 2.4)
         >>> myTuple[:4]   # yields a tuple comprising 1st to 4th element
              (22, 30, 'Hello', 2.4)
         >>> myTuple[4:]  # yields a tuple comprising 5th to last element
              (2, 'Python', (890, 900), 45)
         >>> myTuple[:]   # yields a tuple comprising 1st to last element
              (22, 30, 'Hello', 2.4, 2, 'Python', (890, 900), 45)
         >>> myTuple[::2]  # yields a tuple comprising alternate elements, starting index 0
              (22, 'Hello', 2, (890, 900))
         >>> myTuple[-4]  # yields fourth element from the right end
              2
         >>> myTuple[::-1] # yields a tuple in reverse order
              (45, (890, 900), 'Python', 2, 2.4, 'Hello', 30, 22)




         348   Touchpad Computer Science-XI
   345   346   347   348   349   350   351   352   353   354   355