Computer Science

If a is (1, 2, 3)

  1. what is the difference (if any) between a * 3 and (a, a, a) ?
  2. Is a * 3 equivalent to a + a + a ?
  3. what is the meaning of a[1:1] ?
  4. what is the difference between a[1:2] and a[1:1] ?

Python Tuples

16 Likes

Answer

  1. 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.
  2. Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
  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.
  4. 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.

Answered By

10 Likes


Related Questions