Write the output of the given python code :
# !/user/bin/python
tuple1, tuple2 = (123, ‘xyz’), (456, ‘abc’)
print cmp (tuple1, tuple2) print cmp (tuple2, tuple1) tuple3 = tuple2 + (786,)
print cmp (tuple2, tuple3)
Answers
The output is
-1
1
-1
Explanation:
Tuples are compared position by position: the first item of the first tuple is compared with the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then this is the outcome of the comparison, then the second item is considered, then the third item and so forth.
In the give code snippet,
- tuple1 = (123, ‘xyz’)
- tuple2 = (456, ‘abc’)
- print cmp (tuple1, tuple2)
This statement when executed it falls under the category the first element of tuple1 is < the first element tuple2, so the result is -1.
- print cmp (tuple2, tuple1)
This statement when executed it falls under the category the first element of tuple2 is > the first element tuple1, so the result is 1.
- tuple3 = tuple2 + (786,)
- tuple3 = (456, ‘abc’, 786)
- print cmp (tuple2, tuple3)
This statement when executed it falls under the category the first and second element of tuple2 is equal to the first and second element tuple3. Then further the tuple2 does not have any 3rd element whereas typle3 has 3rd clement, so the result is -1.
The output is
- -1
- 1
- -1