Page 303 - Computer Science Class 11 Without Functions
P. 303
>>> vowels1
('a', 'e', 'i', 'o', 'u')
>>> vowels2 = tuple(['a', 'e', 'i', 'o', 'u'])
>>> vowels
('a', 'e', 'i', 'o', 'u')
>>> vowels3 = tuple({'a', 'e', 'i', 'o', 'u'})
>>> vowels3
('u', 'i', 'e', 'o', 'a')
Note that the elements of the tuples vowel1 and vowels2 appear in the same sequence as those of the string vowels.
However, as the elements of a set are not guaranteed to appear in a specific sequence, the elements of the tuple
appear in random order.
12.10.2 Tuple Assignment
A tuple assignment is often used to assign values to several variables in a single assignment statement. For example,
any of the following we may assign values 30, 'September', 1987 to the variables bDay, bMonth, bYear:
>>> 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)
>>> day = 30, 'September', 1987
>>> myBday = day
>>> myBday
(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.
12.10.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
12.10.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
Lists and Tuples 301

