Computer Science
If a is (1, 2, 3)
- what is the difference (if any) between a * 3 and (a, a, a) ?
- Is a * 3 equivalent to a + a + a ?
- what is the meaning of a[1:1] ?
- what is the difference between a[1:2] and a[1:1] ?
Answer
- a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, 3))
So, a * 3 repeats the elements of the tuple whereas (a, a, a) creates nested tuple. - Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
- This colon indicates (:) simple slicing operator. Tuple slicing is basically used to obtain a range of items.
tuple[Start : Stop] ⇒ returns the portion of the tuple from index Start to index Stop (excluding element at stop).
a[1:1] ⇒ This will return empty list as a slice from index 1 to index 0 is an invalid range. - Both are creating tuple slice with elements falling between indexes start and stop.
a[1:2] ⇒ (2,)
It will return elements from index 1 to index 2 (excluding element at 2).
a[1:1] ⇒ ()
a[1:1] specifies an invalid range as start and stop indexes are the same. Hence, it will return an empty list.
Related Questions
State whether the following statement is True or False :
Functions max( ) and min( ) work with all types of nested tuples.
Discuss the utility and significance of tuples, briefly.
Does the slice operator always produce a new tuple ?
The syntax for a tuple with a single item is simply the element enclosed in a pair of matching parentheses as shown below :
t = ("a")
Is the above statement true? Why? Why not ?