Page 349 - Computer Science Class 11 With Functions
P. 349
It is perfectly fine to drop the parentheses around the comma separated values. For example,
>>> bDate = 30, 'September', 1987
>>> bDate
(30, 'September', 1987)
An empty pair of parentheses defines an empty tuple, for example,
>>> emptyTuple = ()
>>> type(emptyTuple)
<class 'tuple'>
Interestingly, a single value enclosed in parentheses does not define a tuple as it is interpreted as an expression
enclosed in a pair of parentheses. For example,
>>> republic = (1950)
>>> type(republic)
<class 'int'>
>>> republic
1950
To express a tuple comprising a single value, the value in the tuple is followed by a comma, For example,
>>> republic = (1950,)
>>> republic
(1950,)
Examine the following:
>>> t1 = (2, 4, 6)
>>> t2 = (2, 4, 6)
>>> print('id(t1):', id(t1), 'id(t2):', id(t2) )
id(t1): 2402511302272 id(t2): 2402547197696
>>> t1 is t2
False
>>> t1 == t2
True
Note that the two assignment statements create two different instances of tuples. Therefore, the expression t1 is
t2 yields False. However, as t1 and t2 comprise the same sequence of elements, the expression t1 == t2
yields True.
13.7.1 Deriving a Tuple from a String/ List/ Set
The function tuple() is used to construct a tuple from a string, list, or set. For example,
>>> vowels = 'aeiou'
>>> vowels1 = tuple(vowels)
>>> vowels1
('a', 'e', 'i', 'o', 'u')
>>> vowels2 = tuple(['a', 'e', 'i', 'o', 'u'])
>>> vowels2
('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.
13.7.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 to 30, 'September', 1987 to the variables bDay, bMonth,
bYear:
Lists and Tuples 347

